Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return video duration from Youtube API using JSON

I'm trying to retrieve and print the duration of each video that is being returned via the Youtube API using JSON. The duration needs to be out putted like this:

9:34min and not in seconds

But I can't figure out what to do next. I am currently using the following code:

function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul class="videos">'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t.substr(0, 20);
var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
var playerUrl = entries[i].media$group.media$content[0].url;
html.push('<li>',
          '<a href="', playerUrl, '" rel="vidbox 686 315"><img src="', 
          thumbnailUrl, '" width="130" height="97"/></a>', '<span class="titlec"><a      href="', playerUrl, '" rel="vidbox 686 315">', title, '... </a></span></li>');
}
html.push('</ul><br style="clear: left;"/>');
document.getElementById('videos2').innerHTML = html.join('');
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url, false);
}
}
like image 500
Alan Carr Avatar asked Aug 06 '26 05:08

Alan Carr


1 Answers

The YouTube API only outputs the duration in seconds. But you can create a function to convert seconds into the time format you want.

function formatSecondsAsTime(secs) {
    var hr = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600)) / 60);
    var sec = Math.floor(secs - (hr * 3600) - (min * 60));

    if (hr < 10) {
        hr = "0" + hr;
    }
    if (min < 10) {
        min = "0" + min;
    }
    if (sec < 10) {
        sec = "0" + sec;
    }
    if (hr) {
        hr = "00";
    }

    return hr + ':' + min + ':' + sec;
}

Just pass the duration field to the function as so:

var videoTime = formatSecondsAsTime(entries[i].media$group.media$content[0].duration);
like image 126
sbhomra Avatar answered Aug 07 '26 22:08

sbhomra



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!