问题
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:
- 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>
- But delay between
timeupdate
event is pretty big starting from 200ms, so if you want more frequent update control you can trysetInterval
orrequestAnimationFrame
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