I\'m not able to get the correct video duration/length (in seconds) of a loaded/cued video via the getDuration() method of the YouTube Player API; the same method, however,
Following these steps:
1. Get youtube video id
2. Use youtube API to get duration (ISO 8601 duration)
3. Convert ISO 8601 duration to time
Using Jquery:
// convert ISO 8601 duration
function covtime(youtube_time){
array = youtube_time.match(/(\d+)(?=[MHS])/ig)||[];
var formatted = array.map(function(item){
if(item.length<2) return '0'+item;
return item;
}).join(':');
return formatted;
}
// print video duration
$('iframe').each(function(i) {
var ifr = $(this);
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = ifr.attr('src').match(regExp); // get youtube video id
if (match && match[2].length == 11) {
var youtubeUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + match[2]
+ "&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails";
$.ajax({
async: false,
type: 'GET',
url: youtubeUrl,
success: function(data) {
var youtube_time = data.items[0].contentDetails.duration;
var duration = covtime(youtube_time);
if(ifr.next().is('.time')) {
ifr.next().html(duration);
}
}
});
}
});