是否可以以毫秒为单位获取当前的 html5 视频时间帧?

man*_*ioc 2 html video time milliseconds

我正在尝试构建一个实时视频字幕编辑器,并要求 JS/DOM 以毫秒为单位返回当前视频时间帧。根据 DOM,video.currentTime 仅以秒为单位返回值。有没有办法以毫秒为单位获取值?

Sea*_*ous 5

currentTime 包括毫秒。打开 YouTube 视频,打开您的控制台,然后输入 document.getElementsByTagName('video')[0].currentTime;

您将看到时间毫秒及以上: 24.530629


Kar*_*yan 5

ontimeupdate 事件以秒为单位给出你的 currentTime,毫秒分数表示为浮点数,所以如果你想要毫秒精度,你应该乘以 1000。这里有一些方法可以解决它:

  1. 低粒度timeupdate事件跟踪

window.onTimeUpdate = (e) => {
  console.log(Math.round(e.target.currentTime * 1000));
};
Run Code Online (Sandbox Code Playgroud)
<video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' ontimeupdate="onTimeUpdate(event)" controls='controls' autoplay></video>
Run Code Online (Sandbox Code Playgroud)

  1. 但是timeupdate从 200 毫秒开始,事件之间的延迟非常大,因此如果您想要更频繁的更新控制,您可以尝试setIntervalrequestAnimationFrame解决方案,如下所示:

var reqId;

var startTracking = function() {
  console.log(Math.round(video.currentTime * 1000));
  reqId = requestAnimationFrame(function play() {
    console.log(Math.round(video.currentTime * 1000));
    reqId = requestAnimationFrame(play);
  });
};

var stopTracking = function () {
  if (reqId) {
    cancelAnimationFrame(reqId);
  }
};

video.addEventListener('play', startTracking);

video.addEventListener('pause', stopTracking);
Run Code Online (Sandbox Code Playgroud)
<video id="video" src="https://www.sample-videos.com/video701/mp4/240/big_buck_bunny_240p_30mb.mp4" width='320' height='240' controls='controls' autoplay></video>
Run Code Online (Sandbox Code Playgroud)