Always get latest video in YouTube playlist

Bram Vanroy

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.

chammp

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Always get latest video in YouTube playlist

From Dev

Latest youtube video from specific playlist

From Dev

Embed youtube playlist with index; thumbnail is always first video

From Dev

YouTube API v3 get last video in playlist

From Dev

Get all video ID's from a YouTube playlist into a PHP array

From Dev

Get all video ID's from a YouTube playlist into a PHP array

From Dev

YouTube API v3 get last video in playlist

From Dev

Adding video to playlist with Youtube API

From Dev

Scraping YouTube playlist video links

From Dev

Get reference to youtube playlist

From Dev

Get Youtube playlist by Title

From Dev

Get YouTube playlist videos anonymously

From Dev

Regex > get YouTube Playlist ID?

From Dev

how to build video playlist having youtube videos?

From Dev

extract private youtube playlist video links

From Dev

youtube player api - playlist of video not created

From Dev

Get all video informaion from playlist in YouTube API v3

From Dev

Is there a way to add a video to a Youtube playlist through Youtube API as a contributor?

From Dev

Get all videos of a YouTube Playlist in Java

From Dev

Get Youtube publish channel playlist videos in android

From Dev

Adding a video to a playlist using the Youtube Player IFrame API

From Dev

insert video into a playlist with youtube api v3

From Dev

Deleting a video from a playlist with YouTube Data API v3

From Dev

YouTube Objective-C API video url from playlist item

From Dev

Retrieve Video IDs contained in a Playlist - YouTube API v3

From Dev

Regex to extract both video id or playlist id from youtube url

From Dev

Checking if YouTube Video exists in playlist with Google Apps Script

From Dev

How to add multiple youtube playlist with video in my flutter app?

From Dev

Youtube embedded playlist diplays playall button instead of the first video

Related Related

  1. 1

    Always get latest video in YouTube playlist

  2. 2

    Latest youtube video from specific playlist

  3. 3

    Embed youtube playlist with index; thumbnail is always first video

  4. 4

    YouTube API v3 get last video in playlist

  5. 5

    Get all video ID's from a YouTube playlist into a PHP array

  6. 6

    Get all video ID's from a YouTube playlist into a PHP array

  7. 7

    YouTube API v3 get last video in playlist

  8. 8

    Adding video to playlist with Youtube API

  9. 9

    Scraping YouTube playlist video links

  10. 10

    Get reference to youtube playlist

  11. 11

    Get Youtube playlist by Title

  12. 12

    Get YouTube playlist videos anonymously

  13. 13

    Regex > get YouTube Playlist ID?

  14. 14

    how to build video playlist having youtube videos?

  15. 15

    extract private youtube playlist video links

  16. 16

    youtube player api - playlist of video not created

  17. 17

    Get all video informaion from playlist in YouTube API v3

  18. 18

    Is there a way to add a video to a Youtube playlist through Youtube API as a contributor?

  19. 19

    Get all videos of a YouTube Playlist in Java

  20. 20

    Get Youtube publish channel playlist videos in android

  21. 21

    Adding a video to a playlist using the Youtube Player IFrame API

  22. 22

    insert video into a playlist with youtube api v3

  23. 23

    Deleting a video from a playlist with YouTube Data API v3

  24. 24

    YouTube Objective-C API video url from playlist item

  25. 25

    Retrieve Video IDs contained in a Playlist - YouTube API v3

  26. 26

    Regex to extract both video id or playlist id from youtube url

  27. 27

    Checking if YouTube Video exists in playlist with Google Apps Script

  28. 28

    How to add multiple youtube playlist with video in my flutter app?

  29. 29

    Youtube embedded playlist diplays playall button instead of the first video

HotTag

Archive