Jaqx Jaqx - 1 month ago 3x
Javascript Question

Auto-play youtube and soundcloud embeds after one another

I have a music blog that contains a series of youtube and soundcloud embeds.

I would like to automatically play all of the embedded content on the page one after another. In other words after a youtube embed that I've played ends, I would like the next embed to start playing whether it be from soundcloud or youtube and vice versa.

The rendered HTML looks like this:

<span class="soundcloud_embed" id="soundcloud_post_308">
<iframe id="ui-id-1" width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F103518792&show_artwork=true&secret_token=s-LnOTK"></iframe>

<span class="youtube_embed" id="youtube_post_309">
<iframe id="ui-id-2" width="528" height="190" src="//www.youtube.com/embed/Y3CYKXBEtf0" frameborder="0" allowfullscreen></iframe>

<span class="youtube_embed" id="youtube_post_310">
<iframe id="ui-id-3" width="528" height="190" src="//www.youtube.com/embed/yMx1FnkrhYc" frameborder="0" allowfullscreen></iframe>

Building off help I received from this source: Pause Youtube embed when playing Soundcloud embed

To keep track of which players are on the page, which api's they belong to, and which of them is currently playing:

var playerCurrentlyPlaying = {"api":null,"frameID":null};
var players = {"yt":{},"sc":{}};

I need to define a generic playNext function that is called in the event that playerCurrentlyPlaying comes to an end. Depending on the api of the next embed, the playNext function has to execute the proper play command. In order to find which embed is next, the function can perhaps increment the ID of the currentlyPlaying iframe by 1. Such that if id="ui-id-2" has just ended then id="ui-id-3" should play.

Sometimes these youtube videos crash and say things like "video no longer exists" or "uploader has made this unavailable in your country". In these cases, how can I check for a crash and skip to the next incremented ID (e.g. id="ui-id-4") ?

This video no longer exists:

<span class="youtube_embed" id="youtube_post_311">
<iframe id="ui-id-4" width="528" height="190" src="//www.youtube.com/embed/Ym3DgqNTzyc" frameborder="0" allowfullscreen></iframe>


You've got two questions in one, here. I'll try to address them both.

In terms of making the next player auto-play, there are two small steps you'll need to take. The first is to bind your player objects to their API's respective event signaling that the media is done playing. For YouTube, your event listener would look something like this:

 onYTPlayerStateChange = function (event) {
     if (event.data == YT.PlayerState.PLAYING) {
     else if (event.data == YT.PlayerState.ENDED) {

Where playNextPlayer() is this generic function you mention you need to define. For your Soundcloud embeds, your event bindings would look something like this, now:

(function () {
     $(".soundcloud_embed iframe").each(function () {
         var frameid = $(this).attr('id');
         players["sc"][frameid] = {};
         players["sc"][frameid] = {
             "widget": SC.Widget(document.getElementById(frameid)),
                 "firstplay": true
         players["sc"][frameid]["widget"].bind(SC.Widget.Events.READY, function () {
             players["sc"][frameid]["widget"].bind(SC.Widget.Events.PLAY, function () {
                 onSCPlay(frameid, SC.Widget.Events.PLAY);
             players["sc"][frameid]["widget"].bind(SC.Widget.Events.PLAY_PROGRESS, function () {
                 onSCPlay(frameid, SC.Widget.Events.PLAY_PROGRESS);
             players["sc"][frameid]["widget"].bind(SC.Widget.Events.FINISH, function () {

Once you've got those bindings in place, the playNextPlayer function will need to determine what the next player is, what API it comes from, and then execute that API's play call. Something like this:

 playNextPlayer = function() {
  var nextIdNum=parseInt(playerCurrentlyPlaying["frameID"].split("-").pop())+1;
     switch($("#"+nextFrameId).parent().attr('class')) {
         case "youtube_embed":
         case "soundcloud_embed":

Keep in mind that there's no error handling built in to this sample code; you'll have to write some to handle cases where the IDs aren't sequential, for example, or what to do when its out of iframes to play.

As to your second question -- to determine whether or not a video is playable, you'll have to set up some error event listeners as well as the playback event listeners.

function onYouTubeIframeAPIReady() {
     $(".youtube_embed iframe").each(function () {
         players["yt"][$(this).attr('id')] = new YT.Player($(this).attr('id'), {
             events: {
                 'onError': seeError,
                 'onStateChange': onYTPlayerStateChange

The seeError function can then be defined in such a way that it determines what player threw the error (using the event.target.a.id parameter in way similar to how it's being done with the state change event listeners), and then leverages the same generic playNextPlayer function. Keep in mind that if a Youtube video doesn't exist in that way, it will NOT generate a "PLAYING" event, so you'll have to set the proper playerCurrentlyPlaying values in your error listener as well, just to make sure the system then properly advances.

The YouTube player is supposed to throw different types of errors based on whether the video doesn't exist, whether it isn't playable in a particular country, etc. See here: https://developers.google.com/youtube/js_api_reference#Events under the "onError" section to see what these different codes are supposed to be. I say 'supposed to' because it looks like, right now, it's just throwing code 0 for all "can't play" errors.

Here's a working fiddle which does all of the above (you can switch the ids of the soundcloud and youtube iframes to verify that the advancement works both directions). This fiddle also instantiates an onError listener but doesn't define what it will do. Shouldn't be hard for you to get that to work, though.