我正在运行以下代码,它在每个视频的末尾更改html5视频的源,以便它不断地播放一个接一个的视频。在第一个视频结束后,它运行第二个视频,然后运行第三个视频,最终从头开始,导致一个无尽的循环。它还选择了一个随机的起点,但这对我的问题并不重要。
在下面的代码中,您将只找到两个视频源,但最终的代码将使用大约10个视频源。
我的问题是,在一段视频的结尾和下一段视频的开头之间会有一个小停顿。我已经将视频标记的背景颜色设置为红色,这样您就可以在回放每个视频之间看到红色的闪烁。
我猜这个问题可以通过预加载javascript代码中指定的所有视频来解决。因此,我想要实现的是,当当前视频正在播放时,只预加载在javascript代码中指定的列表中的下一个视频。因此,当视频nr。5正在播放,它应该预先加载视频nr。6等。
或者这不是可以通过有效的缓冲/预加载来解决的问题吗?我也很高兴有任何其他的建议..
var vidElement = document.getElementById('video');
var vidSources = [
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});
video { background-color: red }
<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="video" autoplay muted playsinline></video>
<p>(each video is just ~ 10 seconds)</p>
发布于 2018-09-26 08:05:11
您可以使用preload
属性创建video
元素,并将其添加到div容器中,如下所示:
function initVideoElement(videoEl)
{
videoEl.playsinline = true;
videoEl.muted = false;
videoEl.preload = 'auto'; //but do not set autoplay, because it deletes preload
//loadedmetadata is wrong because if we use it then we get endless loop
videoEl.onplaying = function(e)
{
if(++nextActiveVideo == 2)
nextActiveVideo = 0;
//replace the video elements against each other:
if(this.inx == 0)
nextVideoElement = videoElements[1];
else
nextVideoElement = videoElements[0];
nextVideoElement.src = vidSources[nextActiveVideo];
nextVideoElement.pause();
};
videoEl.onended = function(e)
{
this.style.display = 'none';
nextVideoElement.style.display = 'block';
nextVideoElement.play();
};
}
var videoContainer = document.getElementById('videoContainer'),
nextActiveVideo = 0,
nextVideoElement,
videoElements =
[
document.createElement('video'),
document.createElement('video')
],
vidSources =
[
"http://www.w3schools.com/html/mov_bbb.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
videoElements[0].inx = 0; //set index
videoElements[1].inx = 1;
initVideoElement(videoElements[0]);
initVideoElement(videoElements[1]);
videoElements[0].autoplay = true;
videoElements[0].src = vidSources[0];
videoContainer.appendChild(videoElements[0]);
videoElements[1].style.display = 'none';
videoContainer.appendChild(videoElements[1]);
video{background-color: red}
<div id="videoContainer"></div>
https://stackoverflow.com/questions/52503280
复制相似问题