一个小时无法播放一组视频

时间:2019-02-09 08:28:42

标签: javascript html5 css3 video

我有多个视频。现在,下面的代码可以正常工作,因为它可以依次播放多个视频。但是,它们与时间无关,我特别想播放这些视频一小时。如何使用Javascript实现此目标?

<body onload="myNewSrc()">
    <div id="section-title">
        <video onended="myAddListener()" autoplay controls width="100%" height="auto">
            <source src="" type="video/mp4">
        </video>
    </div>
    <script>
        var videoSources = ["http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
            "http://www.html5videoplayer.net/videos/toystory.mp4",
            "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
            "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4",
            "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"
        ];
        var currentIndex = 0;
        //listener function changes src
        function myNewSrc() {
            var myVideo = document.getElementsByTagName('video')[0];
            myVideo.src = videoSources[currentIndex];
            myVideo.load();
        }

        function myAddListener() {
            var myVideo = document.getElementsByTagName('video')[0];
            currentIndex = (currentIndex + 1) % videoSources.length;
            myVideo.src = videoSources[currentIndex];
            myVideo.addEventListener('ended', myNewSrc, false);
        }
    </script>
</body>

2 个答案:

答案 0 :(得分:1)

向正文添加DOMContentLoaded事件侦听器,然后在内部使用Date.now()获取当前时间并将其存储在某个变量中。

然后将存储的时间与每次视频结束播放的当前时间进行比较。如果已超过一个小时,则结束播放。

答案 1 :(得分:1)

您可以这样做

var startTime;
var videoSources = 
["http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.html5videoplayer.net/videos/toystory.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4", "http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4"];
var currentIndex =0;
//listener function changes src
function myNewSrc(){
    startTime = new Date;
    var myVideo = document.getElementsByTagName('video')[0];
    myVideo.src=videoSources[currentIndex];
    myVideo.load();
}
function myAddListener(){

    if ((new Date) - startTime > (60 * 60 * 1000)) {
        return;
    }
    var myVideo=document.getElementsByTagName('video')[0];
    currentIndex=(currentIndex+1)%videoSources.length;
    myVideo.src=videoSources[currentIndex];
    myVideo.addEventListener('ended',myNewSrc,false);
}