Javascript event listener to start video at certain time and stop video after certain duration

好久不见. 提交于 2020-01-01 19:01:41

问题


I'm trying to get my video (locally hosted, not streamed) to start after a certain time and stop after a certain duration. Someone here helped me out here with Javascript, but it's not working for me -- no effect on time of playback at all.

So, in my header, I've called the javascript like this:

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

And the actual javascript looks like this:

// 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:


  1. Wrap your code into a function and invoke that function in document ready or body load event handler, otherwise video variable value may be invalid.
  2. According to 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).

    If you want to start playing the video at 2 seconds and stop at 4 seconds (in the video time stamp), set starttime, endtime to 2, 4 respectively, not 2000, 4000. Furthermore, before seeking to starttime, you must load the video resource once

    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
        }
    }
    


来源:https://stackoverflow.com/questions/8140539/javascript-event-listener-to-start-video-at-certain-time-and-stop-video-after-ce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!