【发布时间】:2016-10-19 10:42:27
【问题描述】:
如何使用 JavaScript 动态播放多个 youtube 或 vimeo 视频?
例如: 我需要有人帮忙完成任务。 我有四个视频。每个视频应该一个接一个地播放,但这四个视频在菜单列表中被标记。默认情况下,第一个视频必须播放剩余的三个视频应该处于非活动状态,当第一个视频完成后,用户需要点击第二个菜单列表。请帮助我,我不知道这个概念
【问题讨论】:
标签: javascript video
如何使用 JavaScript 动态播放多个 youtube 或 vimeo 视频?
例如: 我需要有人帮忙完成任务。 我有四个视频。每个视频应该一个接一个地播放,但这四个视频在菜单列表中被标记。默认情况下,第一个视频必须播放剩余的三个视频应该处于非活动状态,当第一个视频完成后,用户需要点击第二个菜单列表。请帮助我,我不知道这个概念
【问题讨论】:
标签: javascript video
对于 Youtube 来说非常容易。您只需要一个iframe 并在查询字符串(“播放列表”)中提供额外的 YouTube 视频 ID,以逗号分隔。
<iframe
id="p_1_zone_4_video"
onload="oniframeYtLoaded(this)"
style="width:100%; height:100%;border:0 none;"
src="https://www.youtube.com/embed/xKXaEJZxRHQ?loop=1&enablejsapi=1&playlist=yALuTl2THO0,yL1-MUdJ-2I">
【讨论】:
据我了解您的问题,最初只能播放第一个视频。完成后,第二个视频按钮被激活,如果用户点击它,第二个视频就会开始播放。
您需要在保存您的视频信息的对象上添加一个 active(canBePlayed) 属性。只有第一个是真的(所有其他 - 假)。如果视频处于活动状态,则其按钮处于活动状态,否则该按钮被禁用且无法单击。
点击按钮 - 播放视频。在视频结束时,下一个视频处于活动状态。这是检测视频结束的方法:Detect when an HTML5 video finishes
【讨论】:
参考此堆栈:
HTML5 video loop src change on end play function not working
您可以使用视频 html5 标记和 javascript 来实现此目的。请注意,sn-p 无法正常工作,导致视频丢失,但您可以寻找实现目标的方法。
var videosList = ["video1.mp4", "video2.mp4", "video3.mp4", "video4.mp4"]
video_count = 1;
videoPlayer = document.getElementById("homevideo");
function run(){
video_count++;
if (video_count == videosList.length)
video_count = 0;
var nextVideo = "app/video"+videosList[video_count];
videoPlayer.src = nextVideo;
videoPlayer.play();
};
<video id="homevideo" width="100%" autoplay onended="run()">
<source src="app/video1.mp4" type='video/mp4'/>
</video>
如果您需要 youtube 视频,则需要像本例中一样使用 youtube api,并检查 onPlayerStateChange 以播放下一个视频:
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
</body>
</html>
【讨论】: