20

我的页面中有一个 HTML5 视频元素。我要播放的视频时长为10分钟。

我必须从第 1分钟到第 5分钟播放视频的一部分。我可以通过设置它的属性
从特定时间开始它。 但是如何在特定时间停止视频 jQuery 或 JavaScript?currentTime

4

4 回答 4

56

TL;DR:只需听听"timeupdate"

video.addEventListener("timeupdate", function(){
    if(this.currentTime >= 5 * 60) {
        this.pause();
    }
});

在 JavaScript 中等待某事的常用方法是等待事件或超时。在这种情况下超时是没有问题的,用户可以自己暂停视频。在这种情况下,停止不会在您的特定时间,而是更早。

定期检查时间的成本也太高:您要么检查得太频繁(因此浪费宝贵的处理能力),要么检查的频率不够,因此您不会在正确的时间停下来。

然而currentTime,这是一个可检查的属性,幸运的是,还有timeupdate媒体元素的事件,描述如下:

当前播放位置作为正常播放的一部分或以特别有趣的方式改变,例如不连续地改变。

得出的结论是,您可以简单地听timeupdate,然后检查您是否通过了标记:

// listen on the event
video.addEventListener("timeupdate", function(){
    // check whether we have passed 5 minutes,
    // current time is given in seconds
    if(this.currentTime >= 5 * 60) {
        // pause the playback
        this.pause();
    }
});

请记住,只要用户尝试跳过超过 5 分钟,这就会暂停。如果您想允许跳过并且仅在 5 分钟后暂停视频,请删除事件侦听器或引入某种标志:

var pausing_function = function(){
    if(this.currentTime >= 5 * 60) {
        this.pause();

        // remove the event listener after you paused the playback
        this.removeEventListener("timeupdate",pausing_function);
    }
};

video.addEventListener("timeupdate", pausing_function);
于 2013-10-14T08:27:38.287 回答
4

timeupdate事件是您正在寻找的,但它仅以大约 2 fps 的速度触发,这太慢而无法在精确的时间停止。

对于那些我使用的情况requestAnimationFrame,它以 60 fps 触发并稍微减少了 endTime 以修复小的“滞后跳跃”:

const onTimeUpdate = () => {
    if (video.currentTime >= (endTime - 0.05)) {
      video.pause()
    } else {
      window.requestAnimationFrame(onTimeUpdate)
    }
}
window.requestAnimationFrame(onTimeUpdate)
于 2019-04-26T12:26:31.090 回答
0

所以如下

<video id="myVid">
<source></source> <!--Whatever source here -->
</video>

使用上述 HTML 附加事件

var vid = document.getElementById("myVid");
vid.addEventListener("timeupdate", function(){
// Check you time here and
if(t >= 300000) //Where t = CurrentTime
{
vid.stop();// Stop the Video
}
});

这是正确的做法。

于 2013-10-14T08:30:13.880 回答
-1

不确定内置方式,但一种方法是使用 setInterval 函数并检查视频的 currentTime 然后停止播放

var myVid=document.getElementById("video1");
var timer= setInterval(function(){myTimer()},1000);
function myTimer()
  {
    if(myVid.currentTime == 5* 60)
    {
       myVid.pause();
       window.clearInterval(timer);
    }
  }
于 2013-10-14T08:26:01.683 回答