我正在尝试让我的视频(本地托管,而非流式传输)在特定时间后开始并在特定持续时间后停止。这里有人用 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);
最佳答案
- 将您的代码包装到一个函数中,并在文档就绪或正文加载事件处理程序中调用该函数,否则
video
变量值可能无效。 根据 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/