Quantcast
Channel: Living in IT » AJAX
Viewing all articles
Browse latest Browse all 10

Customize Youtube Playlist

$
0
0

How to customize Youtube Playlist so that playlist shows underneath the player? The default youtube embed code has the playlist inside the player and it’s small and not expandable. The following code shows how to customize it.

First step: use Youtube iFrame API to build a player with a playlist

  // include jQuery
  // javascript get origin (protocol and hostname) where YouTube iFrame API and Data API v3 and v2 will run
  var ytPlaylistOrigin =  window.location.protocol + "//" + window.location.host;

  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      // videoId: 'id-of-one-video',
      // if you embed one video only, you need videoID only
      // but not listType and list (for embedding a playlist)
      events: {
        'onReady': onPlayerReady,
        // 'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
        'onStateChange': onPlayerStateChange,
        // 'onError': onPlayerError,
      },
      // playerVars can be found here
      // https://developers.google.com/youtube/player_parameters
      playerVars: {
        listType: 'playlist',
        list: 'IDofaSinglePlaylistYou',
        // Use list when there is only one playlist you want to play.
        // Playlist id starts with 'PL'
        // playlist: ['2nd-video-id','3rd-video-id'],
        // Define a custom playlist of multiple videos along with the first videoId
        // defined above
        autoplay: 1, // default autoplay yes
        controls: 2,
        origin: ytPlaylistOrigin,
        // specify your domain to make this API call secured
      },
    });
  }

  function onPlayerReady(event) {
    // Set volume
    // event.target.setVolume(100);
    currentVideo(0);
    event.target.playVideo();
    // A list of actions on the player can be found here
    // https://developers.google.com/youtube/iframe_api_reference
  }

  function stopVideo() {
    player.stopVideo();
  }

  var currentVideoInList = "";

  function onPlayerStateChange(evt) {
    var videoindex = evt.target.getPlaylistIndex();
    if (currentVideoInList != videoindex) {
      // This marks the current video index
      // Current video index changes when users click on a different video 
      // on the playlist in player or on the playlist outside of the player
      // or a video is finished playing and the player auto advances to the next video 
      currentVideo(videoindex);
      currentVideoInList = videoindex;
    }
  }
  
  // Change style of a playlist item when this item (video) starts to be played
  function currentVideo (vi) {
    $('#ytplaylist > a').removeClass('activeVideo');
    $('#ytvid-'+ vi ).addClass('activeVideo');
  }

  function playVideo(vi) {
    currentVideo(vi);
    player.playVideoAt(vi);
  }

Next: Get titles and thumbnails of all videos in playlist

You need to register for YouTube Data API v3. You will need an API key.

YouTube Data API returns all videos of a playlist regardless if the videos are deleted or private while player generated by iframe API don’t show private/deleted videos. This inconsistency causes the video index doesn’t match between the two API’s.

The solution is to make a synchronous GET request (YouTube API v2) for each videoID that YouTube Data API returns and see if the video exists.

However, later you will find the player generated by iFrame API can return the video index of the current played video and this index could be wrong after a video naturally ends and the player advances to the next video. Bug report

There is no way to overcome this issue..

function check_deleted(str1,callback) {
    $.ajax({
      url: str1,
      async: false,
      success: function() {callback(true);},
      error: function() { callback(false);}
    });
  }

  var url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet" 
     + "&playlistId=aPlaylistIDdoesntStartWithPL" 
     + "&maxResults=50&key=Your_API_Key";

  var apiV2 = "http://gdata.youtube.com/feeds/api/videos/";
  
  // Use jquery to parse json
  $.ajax({
    url: url,
    dataType: 'json',
    success: function(data) {
      var counter = 0;
      var output = '';
      var items = data.items;

      $.each(items, function() {
        var videoTitle = this['snippet']['title'];
        var videoDetail = this['snippet']['description'];
        var videoID = this['snippet']['resourceId']['videoId'];
        var thumbnail = this['snippet']['thumbnails']['medium']['url'];
        var thumbnailw = this['snippet']['thumbnails']['medium']['width'];
        var thumbnailh = this['snippet']['thumbnails']['medium']['height'];
        
        // Check if a video is not deleted
        check_deleted(apiV2+videoID+ytPlaylistOrigin, function(s){
          if (s) {
            output += '<a class="ytPLitem" id="ytvid-' + counter + '" onclick="playVideo(' + counter + ')">'
              + '<span class="ytPLitemIMG"><img src="' + thumbnail + '" /></span>'
              + '<span class="ytPLitemTitle">' + (counter+1) + '. ' + videoTitle + '</span>'
              + '</a>';
            counter++;
          }
        });
      });
      
      $('#ytplaylist').html(output); // Generate playlist in html
    }
  });

The post Customize Youtube Playlist appeared first on Living in IT.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images