1
votes

I am making a music player, by SoundCloud API and SoundManager 2. There is a list of songs that when each one is clicked, that starts playing. But the problem if one song is playing, and I choose another song, the old one does not stop, it keeps playing. So both songs play at the same time. even pressing the same song couple if times, cause the same song plays couple of times. How can I stop the previous song and play the current one?

DEMO http://jsfiddle.net/danials/anU2h/

My code to stream a song by SoundCloud:

SC.stream("/tracks/" + id, function (sound) {
    sound.play({
        whileplaying: function () {
            $(".seekLoad").css('width', ((sound.position / sound.duration) * 100) + '%');
            $(".secPlayed").text(converter(sound.position));
        },
    });
});

To prove that songs are playing all together, I made a seek bad with an element that shows the seconds of current playing song. when a two songs are playing at the same time, the seek bar loaded value and time value keep blinking to show the values of both songs. Just to show the overlap.

Any idea to play one song at the time, and stop whatever was playing?

2

2 Answers

3
votes

The SoundCloud API uses soundManager for the streaming of audio (as you know). Since you're not adding Sound Manager 2 the SoundCloud API adds it for you on the first stream. From SoundCloud API Docs.

The streaming of the SDK is powered by the soundManager2 library. If soundManager2 isn't already present it will be loaded by the SDK.

Sound Manager 2 has a stopAll method which will do what you want. You just had to add this to the beginning of the playIt function. This will check if soundManager exists. If it does it will attempt to stop all audio playing though it. If it doesn't, then we can assume that nothing is playing yet.

if(typeof(soundManager) !== 'undefined'){
    soundManager.stopAll();
}

DEMO

2
votes

The API won't (and shouldn't) inherently have a one-playing-at-a-time check, even though it's pretty integral to their site. It wouldn't be too hard to have a persistent variable is_playing or something, but this would run into issues if you have multiple tabs of the player open.

Is this a use case or is your player a one-page app?