Question

I'm using the SoundCloud Javascript SDK. Recently, the 2.0 SDK was announced, and there no longer seems to be a 'whileplaying' event. In the following code, the 'whileplaying' handler never gets executed.

SC.stream(sound_id, function(sound) {         
  sound.play({
    whileplaying: function() { console.log('whileplaying'); }
  })
);

Am I doing something wrong? If this was taken out of the SDK, is there a workaround?

Was it helpful?

Solution

I'm putting together a Soundcloud audio player for my site and this proved to be a headache: Soundcloud haven't released any docs for the js sdk v2 yet, and it doesn't use soundManager anymore so the streaming audio object is completely different.

Until the docs are available to clarify the situation, you could get by with setInterval or the requestAnimationFrame polyfill to call the audio object's methods (https://developers.soundcloud.com/docs/api/javascript-sdk-2), having stored it in a global variable so you can access it from other functions:

Using setInterval

var updater, scTrack;

function updatePosition(){
  // Do stuff, update timers and transport position
  var loadedPosition = scTrack.getLoadedPosition(),
      currentPosition = scTrack.getCurrentPosition();
  console.log('Current: '+currentPosition+', Loaded: '+loadedPosition);
}

SC.stream(sound_id, function(sound){
  scTrack = sound;
  scTrack.play();
  updater = setInterval( updatePosition, 100);
});

And then with whatever handler you have for a pause or stop button:

scTrack.pause();
clearInterval(updater);

Using requestAnimationFrame

( Polyfill available here: https://gist.github.com/paulirish/1579671 )

var updater, scTrack;

function updatePosition(){
  updater = requestAnimationFrame(updatePosition);
  // Do stuff, update timers and transport position
  var loadedPosition = scTrack.getLoadedPosition(),
      currentPosition = scTrack.getCurrentPosition();
  console.log('Current: '+currentPosition+', Loaded: '+loadedPosition);
}

SC.stream(sound_id, function(sound){
  scTrack = sound;
  scTrack.play();
  updatePosition();
});

For the pause / stop handler:

scTrack.pause();
cancelAnimationFrame(updater);
// This hasn't always cleared the animation request for me so I also set the loop variable to undefined:
updater = undefined;

I'm sure there's a better way of doing it, but it works for now - hopefully the forthcoming docs will clear it up.

OTHER TIPS

By looking into the non-obfuscated JS files (the API itself and the soundmanager file), you can find the events you are looking for.

For example:

    sound._player.on("stateChange", function(state) {
        console.log(state);
    });

Or:

    sound._player.on("positionChange", function(position) {
        console.log(position);
    });

I have quickly testes both for HTML5 and Flash tracks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top