使HTML5视频在指定时间停止 [英] Make HTML5 video stop at indicated time

查看:596
本文介绍了使HTML5视频在指定时间停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面中有一个HTML5视频元素。我想播放的视频持续时间 10 分钟。

I have a HTML5 video element in my page. The video I want to play is having a duration of 10 minutes.

我必须播放视频的一部分,从分钟 1 到分钟 5

我可以通过设置 currentTime 属性从特定时间开始。

但是如何在特定时间停止视频jQuery或JavaScript ?

I have to play the part of the video from minute 1 to minute 5.
I can start it from a particular time by setting its currentTime property.
But how can I stop the video at a particular time jQuery or JavaScript?

推荐答案

TL; DR:只需听一下 timeupdate

TL;DR: Simply listen on "timeupdate":

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






在JavaScript中等待某些东西的常用方法是等待事件或超时。在这种情况下,超时是不可能的,用户可能会自己暂停视频。在这种情况下,停止不会在您的特定时间,但更早。


The usual way to wait for something in JavaScript is to wait for an event or a timeout. A timeout is out of question in this case, the user might pause the video on his own. In this case the stop wouldn't be on your specific time, but earlier.

定期检查时间也太昂贵:您要么经常检查(因此浪费宝贵的处理能力)或不经常,因此你不会在正确的时间停止。

Checking the time regularly is also too costly: you either check too often (and therefore waste precious processing power) or not often enough and therefore you won't stop at the correct time.

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

However currentTime is a checkable property, and to our luck, there's the timeupdate event for media elements, which is described as follows:

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

The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously.

结论是你可以直接听 timeupdate ,然后检查你是否已通过标记:

This concludes that you can simply listen on timeupdate and then check whether you've passed the mark:

// 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分钟标记,请删除事件监听器或引入某种标记:

Keep in mind that this will pause whenever the user tries to skip past 5 minutes. If you want to allow skips and only initially pause the video beyond the 5 minute mark, either remove the event listener or introduce some kind of flag:

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);

这篇关于使HTML5视频在指定时间停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆