The problem is to get the total time the video was played. I am using videojs as a JavaScript library. As a caution, currentTime() method is not what we want as total playback time, we also consider that the viewer seeks the movie to an arbitrary playback position, and wants to acquire the time actually played. example) 60 seconds video Viewer watches first 5 seconds then jumps to the 10 seconds point and watches the next 5 seconds. Current time is 15 seconds point, but I hope total watched time is 10 seconds.
In fact, every time viewer play 10%, call API. How can I implement JavaScript?
edit)
It may be time consuming to read video, so it is difficult to use new Date()
.
For example, 5 seconds video may take 10 seconds due to newtwork speed problem.
I am considering the following code.
As long as you see the console, it works well in most cases, but when you skip the playback position, there is an error in the measurement of the playback rate in rare cases.
<link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
<video id="myPlayer" class="video-js"
controls preload="auto" width="440" height="264"
poster="http://vjs.zencdn.net/v/oceans.png">
<source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
</video>
<script src='https://vjs.zencdn.net/7.4.1/video.js'></script>
const player = videojs('myPlayer');
const trackingPoint = 10;
let totalTime = 0;
let tempTotalTime = 0;
let startTime = 0;
player.on('pause', function () {
totalTime += tempTotalTime;
});
player.on('play', function () {
startTime = player.currentTime();
});
player.on('timeupdate', function () {
if (player.paused()) {
return;
}
let currentTime = player.currentTime();
tempTotalTime = currentTime - startTime;
let tmptotalTime = totalTime + tempTotalTime;
let playbackRate = tmptotalTime / player.duration() * 100;
console.log(Math.floor(playbackRate) + ' %');
});
You'd want to listen to the play
and pause
events for your video player.
For the former, you'd start an incrementer function which basically adds to the total time the video was played, and pause would clear it.
Here's how I would go about it.
let timer = null,
totalTime = 0;
let time = new Date();
player.addEventListener("play", startPlaying);
player.addEventListener("pause", pausePlaying);
function startPlaying() {
timer = window.setInterval(function() {
totalTime += new Date().getTime() - time.getTime()
}, 10);
}
function pausePlaying() {
if (timer) clearInterval(timer);
}
Another alternative:
let isPaused = true;
let time = new Date();
let totalTime = 0;
let t = window.setInterval(function() {
if(!isPaused) {
let milisec = new Date()).getTime() - time.getTime();
totalTime += parseInt(milisec / 1000);
}
}, 10);
player.addEventListener("play", () => isPaused = false);
player.addEventListener("pause", () => isPaused = true);
Hope this helps!