I'm trying to create a simple javascript soundcloud player, based on the trackid that I pass via onclick function.
This is my html:
<div id="gs-play" onclick="play(309689093, this.id)" class="fa fa-3x fa-play">play/pause</div>
<div id="gs-play2" onclick="play(316017522, this.id)" class="fa fa-3x fa-play">play/pause</div>
<div id="gs-play3" onclick="play(315363199, this.id)" class="fa fa-3x fa-play">play/pause</div>
And this is my javascript:
SC.initialize({
client_id: 'CLIENT_ID'
});
var is_playing = false,
sound;
function play(trackid, id){
var id = id;
var url = '/tracks/' + trackid;
if( sound ) {
if(is_playing) {
sound.pause();
document.getElementById(id).classList.toggle('fa-pause');
is_playing = false;
} else {
sound.play();
document.getElementById(id).classList.toggle('fa-pause');
is_playing = true;
}
} else {
SC.stream(url).then(function(obj) {
if (obj.options.protocols[0] === 'rtmp') {
obj.options.protocols.splice(0, 1); }
obj.play();
document.getElementById(id).classList.toggle('fa-pause');
sound = obj;
is_playing = true;
});
}
}
This is working great, but I'm having problems with the play/pause function because, of course, until the song isn't finished sound===false
it will always play/stop the current track even if I clicked on another div. Here's the JSfiddle to better understand the behaviour.
Also, I saw the documentation of SC API but I don't understand how to access to the info of the streamed track (title, duration, artwork...)
EDIT:
I came up with a solution, retrieving the current streaming track with:
SC.get(url).then(function(data){
oldid = data.id;
});
and then pause it if the old id is equal to the new id. I still have some problems with the toggle function (toggle only the one that is playing), I'm trying not to use frameworks. This is the script edited.