Reputation: 23
I have used the YouTube video API in JavaScript
And play pause and stop events I have used
Now I got total current time which total watched time, but my main problem is this:
Watch a video for a few seconds and fast forward, then watch another few seconds and see what time it records.... If I watch a video for 5 seconds, then fast forward to minute 10 and watch another 5 seconds, the time I actually watched the video is 10 seconds, not 10 minutes.
Here is my code :
function onytplayerStateChange(event)
{
//alert("Status=>"+event.data);
if(event. data == 1) {
if(Math.floor(event.target.A.currentTime) == 0) {
previous_track_time = current_track_time = 0;
total_track_time = event.target.A.duration;
} else {
previous_track_time = current_track_time;
current_track_time = event.target.A.currentTime;
}
}
if(event.data == 2)
{
current_track_time = event.target.A.currentTime;
total_track_time =(event.target.A.duration-(current_track_time-previous_track_time));
previous_track_time = current_track_time;
}
}
Can you fix that please?
Upvotes: 1
Views: 2313
Reputation: 7251
If you want the time only watched on a video by a user you need to use a counter. I also simplify your code.
The function onPlayerStateChange:
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
//player play
timer = setInterval(
function() {
seconds++;
console.log("you watch: "+ seconds +" seconds of the video");
}, 1000
);
} else {
//player pause
clearInterval(timer);
}
}
The output : I have see only 8 seconds of the video, the 4 first seconds, and 4 seconds at 2:03
There is a live example (UPDATED)
The full code:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'l-gQLqv9f4o',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
var seconds = 0;
var timer;
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
//player play
timer = setInterval(
function() {
seconds++;
console.log("you watch: "+ seconds +" seconds of the video");
}, 1000
);
} else {
//player pause
clearInterval(timer);
}
}
function stopVideo() {
player.stopVideo();
}
Upvotes: 2