Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 947
whamsicore Avatar asked Oct 22 '25 15:10

whamsicore


1 Answers

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.

like image 180
Tahir Ahmed Avatar answered Oct 25 '25 04:10

Tahir Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!