sonam
sonam

Reputation: 905

Get the duration of an embedded YouTube video

I have an embedded a YouTube player in an iframe. I want to know the duration of video before it starts playing or want to get notified when duration is updated from 0 to actual duration. How can this be done?

Upvotes: 3

Views: 10179

Answers (2)

gre_gor
gre_gor

Reputation: 6801

  1. First you need to include the YouTube Player API library.
  2. The iframe needs the enablejsapi=1 parameter in the URL to work.
  3. Then define a function named onYouTubeIframeAPIReady that will be called when the API library is loaded.
  4. Inside the function initiate the player instance, with an event handler on the "onReady" event.
  5. Inside the event handler you can use player.getDuration() to get the duration in seconds.
<script src="https://www.youtube.com/iframe_api"></script>
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/aqz-KE-bpKQ?enablejsapi=1"></iframe>
function onYouTubeIframeAPIReady() { // function that will be called by the API library
    const player = new YT.Player("player", { // "player" is the id of the iframe
        events: {
            "onReady": event => {
                console.log(`Duration of "${player.videoTitle}": ${player.getDuration()} sec`)
            },
        }
    });
}
// check if API library was already loaded and in that case execute the function yourself
if (window.YT?.Player) {
    onYouTubeIframeAPIReady();
}

You can read more about the API usage in the official YouTube's iFrame API documentation.

Upvotes: 1

Chris Hawkes
Chris Hawkes

Reputation: 12410

According to the Google YouTube api...

Retrieving video information

player.getDuration():Number Returns the duration in seconds of the currently playing video. Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing.

If the currently playing video is a live event, the getDuration() function will return the elapsed time since the live video stream began. Specifically, this is the amount of time that the video has streamed without being reset or interrupted. In addition, this duration is commonly longer than the actual event time since streaming may begin before the event's start time.

Upvotes: 3

Related Questions