问题
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