سؤال

Is there are any way to detect the change of time in getCurrentTime() of YouTube API?

Purpose:To play single video for limited time(<1 min) in my page and move on to next video.

I was thinking to use object.watch but it only works for the variables not the functions.

I also try to bind something in the original source code https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl9twtxR.js but it was too complicated.

هل كانت مفيدة؟

المحلول

Because the YouTube player is wrapped in an iFrame, you are dependent on what the player exposes, and while they've exposed the current time via the getCurrentTime() function, they haven't exposed any events raised whenever the time might get updated (in fact, the time is only updated to the exposed function 6 or 7 times per second, and it isn't always consistent).

So your only option is to set up a javascript timer. Lots of ways to do that; a simple one would be like this:

setInterval(function(){
   // here you'd raise some sort of event based on the value of getCurrentTime();
   },100); // polling 8 times a second, to make sure you get it every time it changes. 

As the postMessage from the iFrame isn't always perfectly consistent, you could have this interval timer be greater. Or you could use something like requestAnimationFrame to poll 60 times a second.

نصائح أخرى

The first example at

https://developers.google.com/youtube/iframe_api_reference#Getting_Started

gives you almost completely exactly what you need to get started. The code there is starting a timer once the video starts then waits 6 seconds to stop the video. What you'd want to do instead of stopping the video after 6 seconds is to fire a new YT.Player instance on the same div after 60 seconds.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top