Always get latest video in YouTube playlist
Asked Answered
G

2

2

I would like to always show the latest video from a playlist. So, only show one video on the page, but always the most recent of a playlist. When a user has uploaded a new video on YouTube, that latest video has to be shown on the webpage.

What I have so far:

HTML

<div id="yt-player"></div>

JS

<script src="http://www.youtube.com/player_api"></script>
<script>
    // create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player("yt-player", {
            height: "480",
            width: "853",
            videoId: "br6xOdlyRbM"
        });
    }
</script>

However, this will only post a video with a specific ID and not from a playlist. I then tried the following JS.

        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player("yt-player", {
              height: "480",
              width: "853",
              playerVars: {
                  listType: "playlist",
                  list: "PLiXK3ub3Pc8_Tk0WiPpVTVmuzoZs8_SaY",
                  color: "white",
                  modestbranding: 1,
                  theme: "light"
              },
              events: {
                "onStateChange": onPlayerStateChange
              }
            });
        }

Unfortunately, this does not work either. The YouTube player is shown, but the first video is shown, and not the last. Live example here.

Gobble answered 5/3, 2014 at 9:13 Comment(0)
E
1

Getting the "last element" of a playlist might not always be what you want - it basically depends on the ordering of videos in the playlist. "Recent Uploads" is (obviously) ordered by upload date descending (newest first), others are by date ascending (oldest first).
In the latter case you have to iterate through all the pages of the playlist until you get to the last item.

There's an example that takes you almost to your target on https://developers.google.com/youtube/v3/code_samples/javascript (code excerpt copied from there):

// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 10
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    // Only show pagination buttons if there is a pagination token for the
    // next or previous page of results.
    nextPageToken = response.result.nextPageToken;
    var nextVis = nextPageToken ? 'visible' : 'hidden';
    $('#next-button').css('visibility', nextVis);
    prevPageToken = response.result.prevPageToken
    var prevVis = prevPageToken ? 'visible' : 'hidden';
    $('#prev-button').css('visibility', prevVis);

    var playlistItems = response.result.items;
    if (playlistItems) {
      $.each(playlistItems, function(index, item) {
        displayResult(item.snippet);
      });
    } else {
      $('#video-container').html('Sorry you have no uploaded videos');
    }
  });
}

The result value nextPageToken is the most interesting one. You have to fetch all pages in order until you get to the last one - in this example you'd have to call requestVideoPlaylist multiple times until response.result.nextPageToken is empty (as this indicates that you reached the last page). The last video in the result list response.result.items is the last video of the playlist (i.e. the most recent one if its ordered by date descending).

To reduce the number of requests (they tend to take some time...) you should increase maxResults in requestOptions to 50 (this is the highest value).

This leads to code like this:

function requestLastVideo(playlistId, callback, pageToken) {
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 50
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    var nextPageToken = response.result.nextPageToken;
    if (nextPageToken) {
      // we didn't reach the last page yet, fetch next one
      requestLastVideo(playlistId, callback, nextPageToken);
      return;
    }

    var playlistItems = response.result.items;
    if (playlistItems) {
      var lastPlaylistItem = playlistItems[playlistItems.length - 1];
      callback(lastPlaylistItem.snippet);
    } else {
      alert('There are no videos');
    }
  });
}

And you'd call this like so:

requestLastVideo("PL91BF7E9AD6889246", function(snippet) {
  console.log('Last video id was ', snippet.resourceId.videoId);
});

You can play around with requestOptions.part to reduce the footprint of your call. With this parameter you can control which fields are present in the response. You can find more information detailling possible values in the YouTube API docs for this call.

Emaciation answered 25/4, 2014 at 7:31 Comment(0)
R
0

You need to get the latest video via API then plug it into your second solution like

  var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player("yt-player", {
          height: "480",
          width: "853",
          videoId: {lastVideoIDinPLAYLIST},
          playerVars: {
              listType: "playlist",
              list: "PLiXK3ub3Pc8_Tk0WiPpVTVmuzoZs8_SaY",
              color: "white",
              modestbranding: 1,
              theme: "light"
          },
          events: {
            "onStateChange": onPlayerStateChange
          }
        });
    }
Recapitulate answered 22/4, 2014 at 16:6 Comment(1)
How do you get lastVideoIDinPLAYLIST? I can't find it in the api.Gobble

© 2022 - 2024 — McMap. All rights reserved.