Javascript事件监听器在特定时间启动视频并在一定时间后停止视频 [英] Javascript event listener to start video at certain time and stop video after certain duration
问题描述
我试图让我的视频(本地托管,而不是流式传输)在一段时间后启动并在一段时间后停止。这里有人用Javascript帮助我,但这对我不起作用 - 根本不会影响播放时间。
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.
所以,在我的标题中,我是称为这样的javascript:
So, in my header, I've called the javascript like this:
<script src="Backend/build/Timer.js"></script>
实际的javascript如下所示:
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);
推荐答案
- 将代码包装进一个函数并在document ready或body load事件处理程序中调用该函数,否则
video
变量值可能无效。 -
根据 W3C标准:
获取时,
currentTime
属性必须返回当前播放位置,以秒表示。在设置时,如果媒体元素具有当前媒体控制器,则它必须抛出INVALID_STATE_ERR异常;否则,用户代理必须寻找新值(这可能引发异常)。
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此外,在寻求 starttime
之前,您必须加载视频资源一次
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
}
}
这篇关于Javascript事件监听器在特定时间启动视频并在一定时间后停止视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!