如何更改暂停的 html5 视频的当前时间并从该位置开始播放

How to change current time of a paused html5 video and start playing from that position?

本文关键字:位置 开始 时间 播放 暂停 何更改 html5 视频      更新时间:2023-09-26

我在这样的页面上有一个html 5视频:

<video preload="none" id="movie" poster="http://my_poster_url.com/sourcefile.jpeg" controls>
     <source id="mp4" type="video/mp4" src="http://my_mp4.com/sourcefile.mp4"></source>
     <source id="webm" type="video/webm" src="http://my_webm.com/sourcefile.webm"></source>
</video>

在该视频下方,我有一个导航,您可以在其中跳到视频中的不同时间。播放视频时它可以完美运行,但是当暂停时会出现以下错误:

无效状态错误:尝试使用的对象不是 或不再可用

这里的函数:

$('#my_video_navigation a').click(function () {
    var start_in_seconds=...//a variable that gets the time from a json based on the navigation index
    $("#movie").get(0).currentTime = start_in_seconds;
    $("#movie").get(0).play();
}

我添加了一个 if/else 语句,无论视频是否暂停:

if ($('#movie').get(0).paused) {
    $("#movie").get(0).play(); 
}

然后尝试像上面一样设置当前时间,甚至使用设置的超时功能,以便它等到视频加载并正在播放,但这不起作用。我做错了什么或忘记了什么?

您应该

更改媒体元素的currentTime字段,如 API 文档中所示。这里还有一个示例代码,在 MDN

作为参考,那里的示例代码:

var mediaElement = document.getElementById('mediaElementID');
mediaElement.seekable.start();  // Returns the starting time (in seconds)
mediaElement.seekable.end();    // Returns the ending time (in seconds)
mediaElement.currentTime = 122; // Seek to 122 seconds
mediaElement.played.end();      // Returns the number of seconds the browser has played

其中mediaElementIDaudiovideo标签的 ID。

编辑:看来我误读了你的问题。我会进一步看看。