来自Youtube API v3的contentDetails,持续时间和统计信息的问题

时间:2016-02-19 17:49:44

标签: javascript jquery youtube-api youtube-data-api

我尝试为每个视频检索durationviewCount的值,两者都在视频下:list api。我创建了一个单独的函数来返回每个视频持续时间和统计信息。唯一有效的是在videoId函数中检索和getPlaylist(...)的视频播放列表。我登录到控制台,这就是我得到的:

console.log("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console

id: xxx duration: undefined viewCount: undefined

我从来没有工作时间,但我注意到带有part: statistics的api将从已注释掉的频道中检索视图总数的值。但这不是我想要的。我想用它来处理每个视频:

GET https://www.googleapis.com/youtube/v3/videos

但出于某种原因,我无法让它发挥作用。我有videoId属性和参数,因此playlistId可以读取它并检索视频的持续时间和查看次数的所述值,但它仍然未定义,即使videoId已经过了定义。哦,警报对话框也没有显示出来。

我在这里缺少什么?

脚本:

var channelName = 'ExampleChannel';
var vidWidth = 500;
var vidHeight = 400; 
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";

$(document).ready(function() {
    $.get( // get channel name and load data
        "https://www.googleapis.com/youtube/v3/channels",
        {
            part: 'contentDetails',
            forUsername: channelName,
            key: 'XXXXXXXXXX'
        },

        function(data)
        {
            $.each(data.items, 
                function(i, item) {
                    console.log(item); // log all items to console
                    var playlistId = item.contentDetails.relatedPlaylists.uploads;
                    //var viewCount = console.log(item.statistics.viewCount);
                    getPlaylists(playlistId);

            })
        }         
    );

    // function that gets the playlists
    function getPlaylists(playlistId)
    {
        $.get(
            "https://www.googleapis.com/youtube/v3/playlistItems",
            {
                part: 'snippet',
                maxResults: vidResults,
                playlistId: playlistId,
                key: 'XXXXXXXXXX'
            },

            // print the results
            function(data)
            {
                var output;
                $.each(data.items, 
                    function(i, item) {
                        console.log(item);
                        var vidTitle = item.snippet.title; // video title
                        var vidDesc = item.snippet.description; // video description
                        var videoId = item.snippet.resourceId.videoId; // video id

                        // check if description is empty
                        if(vidDesc == null || vidDesc == "")
                        {
                            vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
                            $('#desc').remove(); // remove video description
                        }
                        else vidDesc = item.snippet.description;

                        vidDuration = getVideoDuration(videoId);
                        viewCount = getViewCount(videoId);
                        console.log("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console

                        output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';

                    // Append results to list tag
                    $('#results').append(output);
                })
            }         
        );
    }

    // return video duration
    function getVideoDuration(videoId) 
    { 
        $.get(
            "https://www.googleapis.com/youtube/v3/videos",
            {
                part: 'contentDetails',
                id: videoId,
                key: 'XXXXXXXXXX',
            },

            function(data)
            {
                $.each(data.items,
                    function(i, item) {
                        //videoId = item.snippet.resourceId.videoId;

                        alert(item.contentDetails.duration); // video duration
                        //alert(videoId);
                    })    
            }
        );
    }

    // return video view count
    function getViewCount(videoId) 
    { 
        $.get(
            "https://www.googleapis.com/youtube/v3/videos",
            {
                part: 'contentDetails, statistics',
                id: videoId,
                key: 'XXXXXXXXXX',
            },

            function(data)
            {
                $.each(data.items,
                    function(i, item) {
                        //videoId = item.snippet.resourceId.videoId;

                        alert(item.statistics.viewCount); // view count
                        //alert(videoId);
                    })  
            }
        );
    } 
});

屏幕截图:(更新)

enter image description here

1 个答案:

答案 0 :(得分:3)

因为当您调用这些功能时,您不必等待功能完成。 您需要在Javascript中使用Promise

我改变了你的代码(用我的api密钥测试)

var channelName = 'example';
var vidWidth = 500;
var vidHeight = 400; 
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";

$(document).ready(function() {
    $.get( // get channel name and load data
        "https://www.googleapis.com/youtube/v3/channels",
        {
            part: 'contentDetails',
            forUsername: channelName,
            key: 'xxx'
        },

        function(data)
        {
            $.each(data.items, 
                function(i, item) {
                    //console.log(item); // log all items to console
                    var playlistId = item.contentDetails.relatedPlaylists.uploads;
                    //var viewCount = console.log(item.statistics.viewCount);
                    getPlaylists(playlistId);

            });
        }         
    );

    // function that gets the playlists
    function getPlaylists(playlistId)
    {
        $.get(
            "https://www.googleapis.com/youtube/v3/playlistItems",
            {
                part: 'snippet',
                maxResults: vidResults,
                playlistId: playlistId,
                key: 'xxx'
            },

            // print the results
            function(data)
            {
                var output;
                $.each(data.items, 
                    function(i, item) {
                        console.log(item);
                        var vidTitle = item.snippet.title; // video title
                        var vidDesc = item.snippet.description; // video description
                        var videoId = item.snippet.resourceId.videoId; // video id

                        // check if description is empty
                        if(vidDesc == null || vidDesc == "")
                        {
                            vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
                            $('#desc').remove(); // remove video description
                        }
                        else vidDesc = item.snippet.description;

                        getVideoDuration(videoId).done(function(d, v){
                             vidDuration = d;
                             //console.log(r);


                               viewCount = v;

                        document.write("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console

                        document.write("<br>");

                        output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';

                    // Append results to list tag
                    $('#results').append(output);
                   });
                });
            }         
        );
    }

    // return video duration
    function getVideoDuration(videoId) 
    { 
        var dfrd1 = $.Deferred();
        var r = '';
        $.get(
            "https://www.googleapis.com/youtube/v3/videos",
            {
                part: 'contentDetails',
                id: videoId,
                key: 'xxx',
            },

            function(data)
            {
                $.each(data.items,
                    function(i, item) {
                        //videoId = item.snippet.resourceId.videoId;
                        var view = 0;
                        r = item.contentDetails.duration; // video duration 
                        getViewCount(videoId).done(function(t){
                          view = t;
                          dfrd1.resolve(r, view);
                        });

                        //alert(videoId);
                    });    
            }
        );
        return dfrd1.promise();
    }

    // return video view count
    function getViewCount(videoId) 
    { 
        var dfrd2 = $.Deferred();
        var r = '';
        $.get(
            "https://www.googleapis.com/youtube/v3/videos",
            {
                part: 'contentDetails, statistics',
                id: videoId,
                key: 'xxx',
            },

            function(data)
            {

                $.each(data.items,
                    function(i, item) {
                        //videoId = item.snippet.resourceId.videoId;

                        r = item.statistics.viewCount; // view count
                        //alert(videoId);
                        dfrd2.resolve(r);

                      // console.log("in", r);
                    });  
            }
        );
        return dfrd2.promise();
    } 
});

修改

换句话说,这是一个异步方法调用。

getVideoDuration(videoId).done(function(r)

<强>解释

调用函数getVideoDuration.done告诉函数getVideoDuration将在我们解析承诺(dfrd1.resolve(r);)时返回结果。与此同时,函数return dfrd1.promise();意味着结果将被推迟。 当承诺得到解决后,我们输入done,我们可以完成其余的工作:)

你在截图上看到的是合乎逻辑的,因为有两个Promise! 我的错误是我没有看到重复的输入行。 我改变代码来解决这个问题。

所以第一个函数getVideoDuration将被解析,然后是第二个。 解决第二个功能后,我们解决了将结果发送到函数getPlaylists(playlistId)的第一个承诺

编辑25/02

我改变了有关承诺错误的代码。