我正在视频标签中播放多个视频。一切正常。
但是,我需要视频停止循环播放。目前,当所有视频播放完毕后,视频会再次启动,并会再次循环显示所有视频。
要解释此问题,请运行以下代码:
var videoSource = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
$('.playBtn').click(function(e) {
var videoCount = videoSource.length;
var video_index = 0;
function onload() {
videosToPlay = document.getElementById("videosToPlay");
videosToPlay.addEventListener('ended', onVideoEnded, false);
videosToPlay.src = videoSource[video_index];
videosToPlay.play();
}
function onVideoEnded() {
video_index++;
if (video_index > videoCount - 1) video_index = 0;
videosToPlay.src = videoSource[video_index];
videosToPlay.play();
//alert('all the videos played');
}
onload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="" id="videosToPlay" width="320" height="240" controls style="background:black">
</video>
<button class="playBtn">
Play Videos
</button>
如果需要,这是一个FIDDLE:http://jsfiddle.net/bnzqkpza/206/
有人可以就此问题提出建议吗?
提前致谢。
答案 0 :(得分:0)
要解决此问题,您需要修改onVideoEnded()
功能。此时它检测到索引到达videoSource
数组的边界,并将索引重置为0.相反,您需要简单地将逻辑反转为仅在不在数组末尾时继续:
function onVideoEnded() {
video_index++;
if (video_index < videoCount) {
videosToPlay.src = videoSource[video_index];
videosToPlay.play();
}
}
答案 1 :(得分:0)
您的问题就在这一行if (video_index > videoCount - 1) video_index = 0;
当video_index
大于视频计数(-1)时,您重新将video_index
重置为0,即开始。
您可以将其更改为此类
if (video_index > videoCount - 1){
alert("all the videos played");
return;
}
答案 2 :(得分:-1)
即使在视频计数到达之后,您也会重复分配视频源。我刚刚添加了其他语句部分。
错误行
if (video_index > videoCount - 1){
video_index = 0;
videosToPlay.src="#";//
}
videosToPlay.src = videoSource[video_index];//reasigning after ended which causes loop
videosToPlay.play();
更正后的代码段
var videoSource = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
$('.playBtn').click(function(e) {
var videoCount = videoSource.length;
var video_index = 0;
function onload() {
videosToPlay = document.getElementById("videosToPlay");
videosToPlay.addEventListener('ended', onVideoEnded, true);
videosToPlay.src = videoSource[video_index];
videosToPlay.play();
}
function onVideoEnded() {
video_index++;
if (video_index > videoCount - 1){
video_index = 0;
videosToPlay.src="#";
}
else {
videosToPlay.src = videoSource[video_index];
videosToPlay.play();
//alert('all the videos played');
}
}
onload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="" id="videosToPlay" width="320" height="240" controls style="background:black" >
</video>
<button class="playBtn">
Play Videos
</button>