Can not insert multiple videos into a playlist - YouTube API v3

前端 未结 3 1945
小鲜肉
小鲜肉 2021-01-13 13:55

I am trying to add multiple videos to a playlist, but only one video is added to the playlist. I can successful create a playlist and insert a video to the playlist, but can

3条回答
  •  半阙折子戏
    2021-01-13 14:30

    I think I now understand why you need to add a delay. You need to delay each insert request before you send the next one.

    My solution is recursion. Only when I get a response from the request am I sending the next request till the end of the array:

    function addVideoToPlayList(pId, videosIdArray, index)
    {
        var vId = videosIdArray[index];
        var details = {
            videoId: vId,
            kind: 'youtube#video'
        }
    
        var request = gapi.client.youtube.playlistItems.insert({
            part: 'snippet',
            resource: {
                snippet: {
                    playlistId: pId,
                    resourceId: details
                }
            }
        });
    
        request.execute(function(response) {
            console.log(response);
    
            if(videosIdArray.length == index+1)
            {
                // End!
            }
            else{
                addVideoToPlayList(pId,videosIdArray,++index);
            }
    
            $('#status').html(
                $('#status').html() + '
    ' +
                JSON.stringify(response.result) + '

    '); }); }

    Example of how to call this function:

    addVideoToPlayList(destPlaylistId, videosIdArray, 0);
    

提交回复
热议问题