当HTML5 <video>循环重启时,在Javascript中检测?

shs*_*haw 11 javascript video html5

我有一个循环的HTML5视频使用<video loop="true">,我想知道视频何时循环.事件侦听器play仅在最初启动视频时触发,并且ended从不触发.

不精确的性质timeupdate使我紧张使用if ( v.currentTime <= 0 ),但它似乎确实有效.有没有更好的方法来检测视频何时重启?

这是我的基本设置:

<video autoplay="true" loop="true" muted="true">
<source src="vidoe.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<source src="video.ogv" type="video/ogg">
</video>
<div id="Video-Time"></div>

<script>
var v = document.getElementsByTagName('video')[0]
var t = document.getElementById('Video-Time');

v.addEventListener('timeupdate',function(event){
  t.innerHTML = v.currentTime;
  if ( v.currentTime <= 0 ) { console.log("Beginning!"); } // It does trigger when looping, surprisingly
},false);
v.addEventListener('play', function () {
  console.log("play!"); // Only triggered when the video initially starts playing, not when the loop restarts
},false);
v.addEventListener('ended', function () {
  console.log("ended!"); // Never triggered
},false);
</script>
Run Code Online (Sandbox Code Playgroud)

fre*_*nte 12

我认为最可靠的方法是自己循环.删除loop属性并执行以下操作:

document.querySelector('video').addEventListener('ended', function () {
  console.count('loop restart');
  this.play();
})
Run Code Online (Sandbox Code Playgroud)
<video autoplay muted src="https://rawgit.com/bower-media-samples/big-buck-bunny-480p-5s/master/video.mp4"></video>
Run Code Online (Sandbox Code Playgroud)


小智 7

我只需要为移动设备做这个.您无法在移动设备上执行接受的答案,因为移动设备需要用户互动才能再次运行play()(在许多情况下,特别是在大多数Web视图中)

我们在"timeupdate"中唯一可以依赖的是currentTime==0.因为我们知道currentTime==0将在"timeupdate"中运行2-7次取决于硬件/无论什么,我们可以设置一个布尔值来捕获它第一次运行时通过在满足条件后立即将布尔值设置为false,然后在计时器上我们可以重置布尔.

我能想到的最好的解决方案.我们应该只有一个"循环"事件监听器.

let loopCount = 0;
let throttle = true;
document.querySelector('video').addEventListener("timeupdate", () => {
    const video = document.querySelector('video');
    if (video.currentTime === 0 && throttle) {
        throttle = false,
        loopCount += 1;
        console.log(loopCount);
        setTimeout(()=> { 
            throttle = true;
        }, 500);
    }
}, true);
Run Code Online (Sandbox Code Playgroud)
<video autoplay muted loop src="https://rawgit.com/bower-media-samples/big-buck-bunny-480p-5s/master/video.mp4"></video>
Run Code Online (Sandbox Code Playgroud)

  • 我在装有Chrome的Windows计算机上看到的最小的video.currentTime是0.000163。所以不完全是=== 0 ... (2认同)