So while I was trying to create an embedded playlist on my website, and get it to shuffle, I found out that there is a bug in the YouTube API that wasn't fixed and won't let anyone use the Shuffle functionality.
So I'm trying to create a work around. I figured I could make a Random number replace the index number of the playlist. That worked fine, and let me shuffle the playlist, as long as I manually entered the Max and Min for the Random number generator. see it here: http://jsfiddle.net/9kFyx/33/
While I'm very happy with this, I would much rather to have a more dynamic code, which would just get the number of Elements in the playlist array, and use them as a Max number for the Random factor. Sounds easy enough? I looked up the API reference for that here: https://developers.google.com/youtube/js_api_reference#Retrieving_playlist_information
and found player.getPlaylist()
I used array.length;
to get the number array elements, and inject it into the random generator. But it doesn't work! I'm not sure why. When I tried to write the array, it came back as undefined.
Can you help?
<div id="player"></div>
<div id="output" style="width:300px; height:20px; background:white; color:black;">maxNumber</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: '411',
width: '548',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playlistArray;
var playListArrayLength;
var maxNumber;
function onPlayerReady(event) {
player.loadPlaylist({
'listType': 'playlist',
'list': 'PLhaqVbVcY6UPkbjbeJM2CwRedCrr0rPJr'
});
playlistArray = player.getPlaylist();
playListArrayLength = playlistArray.length;
maxNumber = playListArrayLength;
document.getElementById('output').innerHTML = playListArrayLength;
next();
}
function next() {
player.loadPlaylist({
'listType': 'playlist',
'list': 'PLhaqVbVcY6UPkbjbeJM2CwRedCrr0rPJr',
'index': newRandomNumber(),
'startSeconds': '0',
'suggestedQuality': 'small'
});
player.setShuffle({
'shufflePlaylist': 'true'
});
}
var oldNumber = 0;
var NewNumber = 0;
function newRandomNumber() {
oldNumber = NewNumber;
NewNumber = Math.floor(Math.random() * maxNumber);
if (NewNumber == oldNumber) {
newRandomNumber();
} else {
return NewNumber;
}
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
next();
}
}
</script>