Alan Carr
Alan Carr

Reputation: 322

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);
}
}

Upvotes: 3

Views: 2223

Answers (1)

Surinder Bhomra
Surinder Bhomra

Reputation: 2199

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);

Upvotes: 1

Related Questions