如何在页面加载时播放随机视频



我正在尝试在html/js中制作一个随机视频播放器。它应该在页面加载时播放不同的视频,一旦一个视频结束,它应该播放另一个视频。

.HTML

<video width="320" height="240" autoplay>
    <source src="abcdefg.com/example1.mp4" type="video/mp4">
    <source src="abcdefg.com/example2.mp4" type="video/mp4">
</video>

.JS

<script>
var videos = [
    [{type:'mp4', 'src':'abcdefg.com/example1.mp4'}],
    [{type:'mp4', 'src':'abcdefg.com/example2.mp4'}],  
];

$(function() {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
});
</script>

但是,我当前的代码每次重新加载页面都会播放相同的视频,一旦结束,就没有任何反应。

我需要如何优化我的代码,以便在每个页面加载时自动播放不同的视频 + 当上一个视频结束时?

试试这个,我在视频结束属性中添加了一个事件侦听器并调用了newvideo((函数,以便每次视频完成时都会从数组中加载一个新的随机视频。我找不到更多的视频网址,你可以测试并让我知道它是否适合你。

$(document).ready(function(){
var videos = [
    [{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
    [{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
    [{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}]
];
// selecting random item from array,you can make your own
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
    var source = document.createElement('source');
    source.src = src;
    source.type = type;
   element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src)
{
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
//vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(e)
{
newvideo(randomitem[0].src)
}
  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video width="320" height="240" autoplay id="myVideo">
  
</video>

最新更新