Is it possible to get the current html5 video timeframe with milliseconds?

一笑奈何 提交于 2020-05-13 14:15:47

问题


I am trying to build a live video captioning editor and require that the JS/DOM returns the current video timeframe with milliseconds. According to the DOM, video.currentTime only returns the value in seconds. Is there anyway to get the value in/with milliseconds?


回答1:


currentTime includes milliseconds. Open a YouTube video, open your console, then enter document.getElementsByTagName('video')[0].currentTime;

You'll see the time milliseconds and beyond: 24.530629




回答2:


ontimeupdate event gives your currentTime in seconds with milliseconds fraction represented as float number, so if you want milliseconds precision you should multiply by 1000. Here are some ways to approach it:

  1. With low granularity timeupdate event tracking

window.onTimeUpdate = (e) => {
  console.log(Math.round(e.target.currentTime * 1000));
};
<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>
  1. But delay between timeupdate event is pretty big starting from 200ms, so if you want more frequent update control you can try setInterval or requestAnimationFrame solutions, something like this:

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);
<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>


来源:https://stackoverflow.com/questions/44445812/is-it-possible-to-get-the-current-html5-video-timeframe-with-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!