简体   繁体   中英

How to play a song one at the time using SoundCloud API

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM