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

谁说我不能喝 提交于 2019-12-01 07:39:05
Markus Bucher

In addition to Rohan's answer, the function call at the bottom should be:

function myLoop(video_id) {
    addToPlaylist(video_id);
    setTimeout(function() {
        counter++;
        if(counter < links.length)
            myLoop(links[counter]);
    }, 3000);
}

It lacked "video_id" as a parameter.

It worked good for me.

The whole, working code is:

// Global array holds links and a global counter variable
var links = [
  "wtLJPvx7-ys",
  "K3meJyiYWFw",
  "3TtVsy98ces"
]
var counter = 0;

function addVideosToPlaylist() {
    myLoop(links[0]);
}

function myLoop(video_id) {
    addToPlaylist(video_id);
    setTimeout(function() {
        counter++;
        if(counter < links.length)
            myLoop(links[counter]);
    }, 3000);
}
visionix visionix

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() + '<pre>' +
            JSON.stringify(response.result) + '</pre><br/>');
    });
}

Example of how to call this function:

addVideoToPlayList(destPlaylistId, videosIdArray, 0);
Rohan

One solution is to add delays for every insert into a playlist. I'm not entirely sure why a delay is needed though.

I am using a custom loop too with setTimeout();.

Example implementation using delays:

// Global array holds links and a global counter variable
var links = [
  "wtLJPvx7-ys",
  "K3meJyiYWFw",
  "3TtVsy98ces"
]
var counter = 0;

function addVideosToPlaylist() {
    myLoop(links[0]);
}


function myLoop() {
    addToPlaylist(video_id);
    setTimeout(function() {
        counter++;
        if (counter < links.length)
            myLoop(links[counter]);
    }, 3000);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!