Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Multiple Embedded Youtube Videos to Play Automatically in Sequence

Is there any simple way to have multiple embedded YouTube videos on a page and have them start playing as soon as the page is opened and when the first one finished have the second one start?

I was hoping something like this would work:

<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/OdT9z-JjtJk&autoplay=1"></param><embed src="http://www.youtube.com/v/OdT9z-JjtJk&autoplay=1" type="application/x-shockwave-flash" width="425" height="350"></embed></object>
<br>
<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/NlXTv5Ondgs&autoplay=2"></param><embed src="http://www.youtube.com/v/NlXTv5Ondgs&autoplay=2" type="application/x-shockwave-flash" width="425" height="350"></embed></object>

And it does for the first one but not the second. I would imagine that I may need to dive into the API. Anyone have any suggestions?

like image 858
clifgray Avatar asked Mar 04 '13 10:03

clifgray


1 Answers

Using the Youtube IFrame API, you can do this easily.

The only part you need to configure here is the array of youtube IDs. You can retrieve those from the part after the /v/ in the URL (If need be, you can modify the javascript to load URLs instead of IDs. I just like this way better.

<div id="player"></div>
<script src="//www.youtube.com/iframe_api"></script>

<script>
    /**
     * Put your video IDs in this array
     */
    var videoIDs = [
        'OdT9z-JjtJk',
        'NlXTv5Ondgs'
    ];

    var player, currentVideoId = 0;

    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '350',
            width: '425',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        event.target.loadVideoById(videoIDs[currentVideoId]);
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.ENDED) {
            currentVideoId++;
            if (currentVideoId < videoIDs.length) {
                player.loadVideoById(videoIDs[currentVideoId]);
            }
        }
    }
</script>
like image 83
Aaron Saray Avatar answered Nov 05 '22 16:11

Aaron Saray