1
votes

I am making a music player by SoundCloud. It has a "Play/Pause" Button and a play list. By default the "Play/Pause" Button plays the first song of the play list. but if a song in the play list is played so it will be the current song and "Play/Pause" Button works based on that. My problem is that when I select a song, it starts playing but the previous song does not stop. unless I press "Play/Pause" Button before clicking on another song.

Here is the code:

var currentTrack = $("ul li").first().attr('id');

Finds the id val of the clicked item so this id will be song code to play.

$(document).ready(function(){
    $("ul").on('click','li',function(){
        currentTrack = this.id;
        console.log(currentTrack);
        streamTrack(currentTrack);
    });

}); 

If the current song is alrealy playing the pressing button pause it, if not play it (toggle). Else play default item

var is_playing = false,
    sound;
function player(){

    if( sound ) {
        if(is_playing) {
            sound.pause();
            is_playing = false;
        } else {
            sound.play();
            is_playing = true;
            console.log(already_played);
        }
    } else {
        currentTrack = $("ul li").first().attr('id');
        console.log(currentTrack);
        streamTrack(currentTrack);
    }
} 

The method to play a song.

var is_playing = true;
function streamTrack(myTrack){
    SC.stream("/tracks/" + myTrack, function(obj){
            //obj.stopAll();

            obj.play();
            sound = obj;
            is_playing = true;
    });
}

Here is the online demo: http://jsfiddle.net/danials/wZZ4D/10/

Any idea, how to stop all songs playing and play the one is clicked?

1

1 Answers

0
votes

you don't need to make a whole function for it just make sound global and pause sound or stop it sound is not null.

do like this:

var sound;
$(document).ready(function(){

        $("ul").on('click','li',function(){
            currentTrack = this.id;
            console.log(currentTrack);
            if(sound)   // check if sound not null pause it
               sound.pause();
            streamTrack(currentTrack);
        });

});

UPDATED FIDDLE