Dtorr1981
Dtorr1981

Reputation: 263

Play random youtube video from list/playlist and loop

We have a number of clients who have youtube video advertisements. These are currently in a YouTube playlist, but by embedding the playlist, the same video is always displayed first on the website so we want to randomise which video is displayed on pageload from the playlist. I have a code snippet which will load a random video from the input video url however when the video is finished it does not move on to the next video in the list. Could anyone suggest how I can accomplish what I am trying to do? My code is below.

    <!-- Youtube video loop playlist -->
<script>
        var videos = ["https://www.youtube.com/embed/9bZkp7q19f0", "https://www.youtube.com/embed/dQw4w9WgXcQ", "https://www.youtube.com/embed/CzJ-h7W1hVw"];
        window.onload = function () {
            var playerDiv = document.getElementById("random_player");
            var player = document.createElement("IFRAME");
            var randomVideoUrl = videos[Math.floor(Math.random() * videos.length)];
            player.setAttribute('width', '528');
            player.setAttribute('height', '330');
            player.setAttribute('src', randomVideoUrl);
            playerDiv.appendChild(player);
        };
        onStateChange: function(e){
            var id = 'qzZuBWMnS08';

            if(e.data === YT.PlayerState.ENDED){
                player.loadVideoById(videos);
            }
        }
    </script>
<div id="random_player"></div>

Thank you in advance. Donna

Upvotes: 1

Views: 5420

Answers (1)

Thatkookooguy
Thatkookooguy

Reputation: 7022

The function loadVideoById can either get a single ID or a single video in an object syntax. It can't receive an array of videos or a playlist.

Here's my implementation http://jsfiddle.net/thatkookooguy/e11oy0eu/2247/ (code also embedded at the end)

Notice that the setTimeout is used since there's a bug with the youtube API. if you set either setShuffle or playVideoAt immediately, nothing happens (or the playlist resets and starts from the beginning).

You can add anything else you want to change in the player's playback options (shuffle, loop). If it doesn't work as is, try to add those parameters to the setTimeout as well.

reference: youtube API - setShuffle don't work

// This code loads the IFrame Player API code asynchronously.
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;

// load the playlist
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    events: {
      'onReady': onPlayerReady
    },
    playerVars: {
      listType: 'playlist',
      list: 'PLOy0j9AvlVZPto6IkjKfpu0Scx--7PGTC'
    }
  });
}

// when the video player is ready, generate a random number, and play from that
function onPlayerReady(event) {
  // create a random number between 0 and 149
  num = Math.floor(Math.random() * 150);

  // the timeout is set because of a bug with the youtube API. if you do any of this line without it, it won't affect anything
  // see: https://stackoverflow.com/questions/12916017/youtube-api-setshuffle-dont-work
  setTimeout(() => {
    player.playVideoAt(num);
  }, 1000);
}
<div id="player"></div>

Upvotes: 3

Related Questions