Reputation: 39
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);
Upvotes: 2
Views: 13587
Reputation: 3926
video
variable value may be invalid.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
}
}
Upvotes: 7