Reputation: 905
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
Reputation: 6801
enablejsapi=1
parameter in the URL to work.onYouTubeIframeAPIReady
that will be called when the API library is loaded.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
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