0

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?

http://jsfiddle.net/42S5N/

<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>
1

2 Answers 2

1

There's a delay between calling player.loadPlaylist() and being able to get the playlist with player.getPlaylist(). This answer provides a fix by waiting for the CUED event, but in my tests it wasn't being fired at all, so I checked for the PLAYING event which worked fine.

Your code would be something like this:

function onPlayerReady(event) {
    player.loadPlaylist({
        'listType': 'playlist',
        'list': 'PLhaqVbVcY6UPkbjbeJM2CwRedCrr0rPJr'
    });
}

var firstLoad = true;
function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
        next();
    } else {
        if (firstLoad && event.data == YT.PlayerState.PLAYING) {
            firstLoad = false;
            playlistArray = player.getPlaylist();
            playListArrayLength = playlistArray.length;
            maxNumber = playListArrayLength;
            document.getElementById('output').innerHTML = playListArrayLength;
            next();
        }
    }
}
1

My solution in PHP, a little overwhelming, but it works.

function getNumberofElements() {
    $pid = $this->getPID();
    $url = "https://www.googleapis.com/youtube/v3/playlists?part=contentDetails&id=$pid&key=$yourAPIKey";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
    curl_setopt($ch, CURLOPT_POST, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, FALSE);
    curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
    curl_setopt($ch, CURLOPT_REFERER, "");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");

    $numberOfElements = curl_exec($ch);  // $xml = simplexml_load_string($numberOfElements);

    $numberOfElements = substr(strstr($numberOfElements, 'itemCount":'), strlen('itemCount":'));
    $numberOfElements = str_replace("}", " ", $numberOfElements);
    $numberOfElements = str_replace("]", " ", $numberOfElements);

    return $numberOfElements;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.