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?
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?
Share Improve this question edited Nov 5, 2023 at 16:09 gre_gor 6,77411 gold badges73 silver badges88 bronze badges asked Apr 24, 2014 at 12:54 sonamsonam 9053 gold badges18 silver badges37 bronze badges 1- 30 seconds google search developers.google./youtube/iframe_api_reference this may help you – Poomrokc The 3years Commented Apr 24, 2014 at 12:58
2 Answers
Reset to default 3According 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 monly longer than the actual event time since streaming may begin before the event's start time.
- First you need to include the YouTube Player API library.
- The iframe needs the
enablejsapi=1
parameter in the URL to work. - Then define a function named
onYouTubeIframeAPIReady
that will be called when the API library is loaded. - Inside the function initiate the player instance, with an event handler on the "onReady" event.
- Inside the event handler you can use
player.getDuration()
to get the duration in seconds.
<script src="https://www.youtube./iframe_api"></script>
<iframe id="player" width="560" height="315" src="https://www.youtube./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.