youtubeyoutube-api

Embedding Youtube playlist but starting from random video


I've done plenty of searching but can't find a olsution so far...

I have a Youtube playlist. I want to embed it on a website. But instead of always starting at the first video, I want it to start at either a random video, or a at least a specific video (which I can randomly select with server side code).

I have looked at the options for the iframe embed URL and can't see a parameter that allows me any control over this. Is it possible to do?

Otherwise I presume I would need to do something in JavaScript with the API. Can someone paste or point me to some example code that I could use to accomplish this as I haven't used the Youtube API before?


Solution

  • Generate a random number on your server and then use the index parameter in the url. Here's an example where the playlist will start on the 7th item by adding index=7.

    <iframe width="560" height="315" src="http://www.youtube.com/embed/videoseries?list=PL9C5815B418D1508E&index=7" frameborder="0" allowfullscreen></iframe>
    

    The other option is to use the js api, and call loadPlaylist and include the index argument. https://developers.google.com/youtube/js_api_reference#loadPlaylist

    **Edit: Since Google introduced YouTube's 3.0 API, the index parameter is now zero-based. Therefore, if we wanted to start at the 7th video, we'd modify the example above using &index=6 instead of &index=7.

    (Link: https://developers.google.com/youtube/iframe_api_reference#Queueing_Functions_for_Playlists)


    Edit 2024: index param doesn't work anymore. You can accomplish this with the iframe api instead Start YouTube embed playlist at a specific video/index