Search code examples
javascriptyoutubejsfiddleplaylistjsapi

Get reference to youtube playlist


I can't get reference to YouTube playlist video.

This doesn't work JSFIDDLE

I don't even know its real to enable jsapi in playlist?

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('movie_player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady() {
  console.log("hey Im ready");
//do whatever you want here. Like, player.playVideo();

}

function onPlayerStateChange() {
  console.log("my state changed");
}

Solution

  • I think the below code can help you get started, cos I didn't understood correctly what you're trying to achieve. But I understood that you need to play and pause the video. So below is the code which I used somewhere in my project-

    function toggleVideo(state) {
            if(state == 'pause'){
                document.getElementById('movie_player').contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
            }
            else {
                document.getElementById('movie_player').contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
            }
        }
    

    UPDATE I have completely understood now, below are the steps how you can achieve this-

    1) Get Json data for the playlist using the code below-

    var playlistId = 'PL1HIp83QRJHRbmJl0sS0CLOuIKCBCB76L';
    $.getJSON('https://gdata.youtube.com/feeds/api/playlists/'+ playlistId +'?v=2&alt=jsonc',function(data,status,xhr){
    // save json data of the playlist
    }).error(function() { alert("404 Error"); });
    

    See the XML format in the below url, you can get the same data in JSON format by using "&alt=jsonc" in the API url- https://developers.google.com/youtube/2.0/developers_guide_protocol_playlists#Retrieving_a_playlist

    2) Create two iframes or containers in which you need to keep two youtube players. First one will be the player which you should pause after each 10 minutes or so and when paused you should hide the first container. The second instance should hold the player which should have the second video which should play till completed, on complete hide this container and again show the first container.

    See this post on how to play and pause youtube videos- How to pause a YouTube player when hiding the iframe?

    3) After each 10 minutes or so, get the next video link and details from the JSON data of the playlist and link it to the second container pausing & hiding the first one and playing & showing the second one.

    I hope in this way you can achieve what you require.