[Javascript] Youtube 播放清單的隨機撥放

2018-01-05

最近想寫點好玩的東西,想要隨機撥放某個撥放清單,但是,根據官方的設定好像找不到或是不能用,看一下論壇罵聲一片,後來看了許多文件找到一個解決方法這邊完整的提供出來,謝謝這世界各位大大的分享..

image

Code :

    <script
        src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

    <div id="player" style="width: 240px; height: 180px"></div>

    <button type="button" id="btnPlay">點我隨機撥放</button>
    <script>

        var playlistId ='PLf5SPN8zFp6Gb98nAvUNii-ieMrYtsEkL'
        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;

        var listCount = 199;

        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',

                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                },
                playerVars:
                {
                    listType: 'playlist',
                    list: playlistId,
                    'suggestedQuality': 'small'
                }
            });


        }
        
        function onPlayerReady(event) {
            
        }

        //判斷是不是第一次撥放的Flag
        var isFirstPlay = true;
        function onPlayerStateChange(event) {
            //如果是播完就呼叫撥下一首
            if (event.data == YT.PlayerState.ENDED) {
                PlayNext();
            } else {
                //如果是第一次播放取得清單
                if (isFirstPlay && event.data == YT.PlayerState.PLAYING) {
                    isFirstPlay = false;
                    playlistArray = player.getPlaylist();
                    //因為這在這才能取到list 的總數是多少
                    listCount = playlistArray.length;
                    PlayNext();
                }
            }
        }
        function stopVideo() {
            player.stopVideo();
        }

        function PlayNext() {
            var rnd = getRandomInt(0, listCount - 1);
            player.loadPlaylist({
                'listType': 'playlist',
                'list': playlistId,
                'index': rnd
            });
            player.playVideo();
        }


        //取 min ~ max 整數亂數
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }


        $(document).ready(function () {
            $('#btnPlay').click(function () {

                player.playVideo();
            });
        });

    </script>

sample:
reference :https://stackoverflow.com/questions/23566131/shuffle-playlist-fix-for-youtube-api


當麻許的超技八 2014 | Donma Hsu Design.