Get video duration with YouTube Data API?

这一生的挚爱 提交于 2019-12-05 01:42:44
squiroid

I searched your query and found there's an issue with the search api.

The alternative is to make a call to the Youtube Data API's Video resource after you make the search call. You can put up to 50 video id's in search, so you won't have to call it for each element

I updated your codepen and what I done was the following:

1) Get Url of each video that you got from search.

2) Send an another Ajax call to get duration:-

for (var i = 0; i < data.items.length; i++) {
    var url1 = "https://www.googleapis.com/youtube/v3/videos?id=" + data.items[i].id.videoId + "&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails";
    $.ajax({
        async: false,
        type: 'GET',
        url: url1,
        success: function(data) {
            if (data.items.length > 0) {
                var output = getResults(data.items[0]);
                $('#results').append(output);
            }
        }
    });
}

3) The API give time in ISO format so I converted it into mm:ss format (as you wanted).

function convert_time(duration) {
    var a = duration.match(/\d+/g);

    if (duration.indexOf('M') >= 0 && duration.indexOf('H') == -1 && duration.indexOf('S') == -1) {
        a = [0, a[0], 0];
    }

    if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1) {
        a = [a[0], 0, a[1]];
    }
    if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1 && duration.indexOf('S') == -1) {
        a = [a[0], 0, 0];
    }

    duration = 0;

    if (a.length == 3) {
        duration = duration + parseInt(a[0]) * 3600;
        duration = duration + parseInt(a[1]) * 60;
        duration = duration + parseInt(a[2]);
    }

    if (a.length == 2) {
        duration = duration + parseInt(a[0]) * 60;
        duration = duration + parseInt(a[1]);
    }

    if (a.length == 1) {
        duration = duration + parseInt(a[0]);
    }
    var h = Math.floor(duration / 3600);
    var m = Math.floor(duration % 3600 / 60);
    var s = Math.floor(duration % 3600 % 60);
    return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s);
}

4) Append your result with title of your video.

'<p class="cTitle">' + channelTitle + '  --->' + duration + '</p>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!