YouTube Player API: getDuration(), getCurrentTime(), getVideoData() not working

僤鯓⒐⒋嵵緔 提交于 2019-12-07 19:46:07

问题


For my application, I am trying to use the YouTube Iframe player API to play videos, and allow the user to change videos without reloading the page.

I accomplish this by using the player.loadVideoById(video_id) method. After loading the video via YouTube video id, I also want to capture all relevant information about the video. However, I notice that none of the get functions work right away, including getDuration(), getCurrentTime() and getVideoData().

I have found a scrappy solution of using a setTimout to get the information about 1-2 seconds after using player.loadVideoById(video_id), however, I do not think this is the proper solution.

It seems to me that loadVideoById(video_id) is asynchronously fetching the data from YouTube. Is there a callback function available to use? I could not find one in the docs. Please help.

Thanks!


回答1:


There are quite a few Events available that you can utilise I think.

Here is an example of tracking YT.PlayerState.PLAYING state, falling within the onStateChange event, which is basically saying that the video is currently being played.

player.addEventListener(YT.PlayerState.PLAYING, onVideoPlaying, false);

function onVideoPlaying() {
  console.log('currentTime:', player.getCurrentTime(), 'duration:', player.getDuration());
}

Hope this helps.



来源:https://stackoverflow.com/questions/32001561/youtube-player-api-getduration-getcurrenttime-getvideodata-not-working

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