How to detect change in youtube getCurrentTime()?

天涯浪子 提交于 2019-12-11 12:57:16

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/22650281/how-to-detect-change-in-youtube-getcurrenttime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!