I searched a lot a way to get the seconds of a video view for a user thet visit my site. The videopage have embed youtube videos and I need the number of seconds view for posting on facebook. Rules said:
If the person watches more than 50% of a video, but does not complete it, the action instance should be updated to reflect that the person has stopped watching by updating expires_in to the length of time the video was actually watched from: http://developers.facebook.com/docs/opengraph/guides/video.watches/
So far I have the following code where I improvised. When user press start video I start a counter. The problems are in the code comments.
function stopCycle(event) {
switch( event.data ) {
//event.data can be 1 or 2 . If user press play is event.data = 1 and if press
pause event.data = 2 and again if press play will be case 1. So each time
when user press START - PAUSE - CONTINUE - PAUSE event.data will have the value
case 1:
// here i post on facebook after 10 seconds as rules said
setTimeout('postwatch()', 10000);
//i get with ajax from youtube the video time (in seconds)
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/<?php echo get_post_meta(get_the_ID(), 'tj_video_id_url', TRUE); ?>?alt=json",
dataType: "jsonp",
success: function (data) {
//here I appeal the ontimer function but the bug is that every tine i press play button even and after pause get appeal and the counter got crazy
onTimer(data.entry.media$group.yt$duration.seconds);
}
});
break;
}
console.log("onStateChange has fired!
New state:" );
}
i = 0;
function onTimer(videotime) {
document.getElementById('mycounter').innerHTML = i;
i++;
if (i > videotime) {
alert('Finish!');
}
else {
setTimeout(onTimer, 1000);
}
}
Do you know any alternative or can answer me a correct method for me?
I made this as alternative but i have some delay, when i click pause video, the timer stop but when i press play the timer already start with + 1 second but in video i may pause on second 4,5 and my timer go from 5:
var started = 0;
function stopCycle(event) {
switch( event.data ) {
case 1:
ispaused = false;
if(started == 0) {
setTimeout('postwatch()', 10000);
onTimer(youtube.youtubeinfo.entry.media$group.yt$duration.seconds, 0);
started = 1;
}else if(started == 1) {
onTimer(youtube.youtubeinfo.entry.media$group.yt$duration.seconds, i);
}
break;
case 2:
setPause();
console.log('pauz');
break;
}
}
var ispaused=false;
function setPause(){
ispaused=!ispaused;
}
i = 0;
function onTimer(videotime, remaining) {
if(!ispaused) {
document.getElementById('mycounter').innerHTML = i;
if(remaining > 0) {
i = remaining;
console.log('ramas');
}
console.log(i);
if (i > videotime) {
alert('Finish!');
}else{
setTimeout(onTimer, 1000);
}
i++;
}
}