Javascript事件监听器在特定时间开始视频并在一定时间后停止视频

标签 javascript video html5-video

我正在尝试让我的视频(本地托管,而非流式传输)在特定时间后开始并在特定持续时间后停止。这里有人用 Javascript 帮助我,但它对我不起作用——对播放时间根本没有影响。

因此,在我的标题中,我这样调用了 javascript:

<script src="Backend/build/Timer.js"></script>

而实际的 javascript 看起来像这样:

// JavaScript Document

var starttime = 2000;  // start at 2 seconds
var endtime = 4000;    // stop at 4 seconds

var video = document.getElementById('player1');
video.currentTime = starttime;

video.addEventListener("timeupdate", function() {
    if (video.currentTime >= endtime) {
        video.pause();
    }
}, false);

最佳答案

  1. 将您的代码包装到一个函数中,并在文档就绪或正文加载事件处理程序中调用该函数,否则 video 变量值可能无效。
  2. 根据 W3C standard :

    The currentTime attribute must, on getting, return the current playback position, expressed in seconds. On setting, if the media element has a current media controller, then it must throw an INVALID_STATE_ERR exception; otherwise, the user agent must seek to the new value (which might raise an exception).

    如果你想在2秒开始播放视频并在4秒停止播放(在视频时间戳中),将starttime, endtime分别设置为2, 4 , not 2000, 4000. 此外,在寻求 starttime 之前,您必须加载一次视频资源

    function playVideo() {
        var starttime = 2;  // start at 2 seconds
        var endtime = 4;    // stop at 4 seconds
    
        var video = document.getElementById('player1');
    
        //handler should be bound first
        video.addEventListener("timeupdate", function() {
           if (this.currentTime >= endtime) {
                this.pause();
            }
        }, false);
    
        //suppose that video src has been already set properly
        video.load();
        video.play();    //must call this otherwise can't seek on some browsers, e.g. Firefox 4
        try {
            video.currentTime = starttime;
        } catch (ex) {
            //handle exceptions here
        }
    }
    

关于Javascript事件监听器在特定时间开始视频并在一定时间后停止视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8140539/

相关文章:

javascript - Cordova |发送视频到手机

html5-canvas - 如何将多个 WebRTC 媒体流(屏幕截图 + 网络摄像头)混合/组合成一个流?

javascript - 我的播放列表插件无法在 videojs 上运行?

javascript - 不理解这个在网格中生成复选框的剑道模板

javascript - JavaScript 是否等待此 DOM 事件完成?

.net - 使用 Flash 或 .NET 以移动图像作为叠加层的视频

html - 如何在html中反向播放视频

javascript - Angular : view not updating

php - 通过 POST 将数组从 Javascript 传递到 PHP

android - 确认使用服务器观看了 admob 奖励视频