Search code examples
javascriptyoutube-api

YouTube API playlist shuffle not working?


I have been trying to set-up my youtube api to shuffle my playlist but the order is the same all the time...

Here is the link where I am getting my code from https://developers.google.com/youtube/iframe_api_reference#setShuffle

Am I calling it right?

here is my code below

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

<script>

  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('player', {
      height: '390',
      width: '640',
      events: {
        'onReady': onPlayerReady
      }

    });
  }



  function onPlayerReady(event) {
    player.loadPlaylist({'listType': 'playlist', 'list': 'PLF776D41D8211F340','index': '0','startSeconds': '0','suggestedQuality': 'hd720'});
    player.setShuffle({'shufflePlaylist' : 1});

  }

</script>

I have tried setting shufflePlaylist to 'true', I have tried cueplaylist instead of loadplaylist and I have even tried putting the shufflePlaylist in the load Playlist...nothing is getting shuffled.

I have looked into this and I see that it was an issue with the API, but that was 2 years ago, is there a solution to this issue?

Below is what I have tried and didn't work

player.setShuffle(1);
        player.setShuffle('1');
        player.setShuffle(true);
        player.setShuffle('true');
        player.setShuffle({'shufflePlaylist' : true});
        player.setShuffle({'shufflePlaylist' : 1});
        player.setShuffle({'shufflePlaylist' : 'true'});
        player.setShuffle({'shufflePlaylist' : '1'});

I have also tried copying and example from here....https://developers.google.com/youtube/youtube_player_demo

The Shuffle works here after u load the playlist and click a button.


Solution

  • This is a known bug that is yet to be fixed - see this post

    A work around however is to pass a random number to playVideoAt, as follows:

    var getRandom = function(min, max) {
      return Math.random() * (max - min) + min;
    };
    
    var playRandomTrack = function() {
      num = getRandom(0, 99);
      player.playVideoAt(num);  
    };