Vitor Venturin
Vitor Venturin

Reputation: 1289

Soundcloud Widget - Event.PLAY not working

I'm having problems with the SoundCloud Widget API.

For some reason the Event.PLAY is not working anymore...

var i, song, iframes = document.getElementsByTagName('iframe');

for (i = 0; i < iframes.length; i++) {
    if (String.prototype.indexOf.call(iframes[i].src, '//w.soundcloud.com/player') > -1) 
    {           
        iframes[i].id = "sc_player_"+i;
        song = SC.Widget(iframes[i].id);                    
        song.bind(SC.Widget.Events.PLAY, function(eventData){               
            song.getCurrentSound(function(sound) {
                console.log(sound.title);
            });
        });
    }
}

Upvotes: 1

Views: 652

Answers (1)

Misha Reyzlin
Misha Reyzlin

Reputation: 13906

Thanks for reporting this, we are looking into why the PLAY event doesn't fire on first play right now.

UPD. The bug with PLAY event not firing on initial play was fixed now.

On a side note, there's a problem with your code: the functions you are creating (event handlers) inside of the loop will all reference the last iframe as song. You should either wrap the event handler creation in an IFFE passing the current song as a paramater:

for (i = 0; i < iframes.length; i++) {
    if (src.indexOf('//w.soundcloud.com/player') > -1) {           
        iframes[i].id = "sc_player_"+i;
        song = SC.Widget(iframes[i].id);
        song.bind(SC.Widget.Events.PLAY, (function (song) {
            return function(eventData){               
                song.getCurrentSound(function(sound) {
                    console.log(sound.title);
                });
            }
        }(song)));
    }
}

Or create a helper function that will return an event handler referencing the right song:

function createEventHandler (song) {
  // `song` will be “caught” in the closure
  return function (eventData) {
    song.getCurrentSound(function (sound) {
      console.log(sound.title);
    });
  }
}

for (i = 0; i < iframes.length; i++) {
    if (src.indexOf('//w.soundcloud.com/player') > -1) {           
        iframes[i].id = "sc_player_"+i;
        song = SC.Widget(iframes[i].id);
        song.bind(SC.Widget.Events.PLAY, createEventHandler(song));
    }
}

Upvotes: 1

Related Questions