问题
Using the Soundcloud JavaScript SDK I have successfully been able to grab my tracks and play them. My goal is to allow playing and pausing via clicking on one button (like a play/pause toggle). However, my issue is that when I click on the .SCbtn element, the song plays, and doesn't stop. My conditionals seem to be correct because I can see true and false making it into the console. Not quite sure why SC.sound.pause(); isn't working.
var is_playing = false;
var trackCont = function(trackNum){
SC.stream("/tracks/" + trackNum).then(function(sound){
SC.sound = sound;
if (is_playing === false){
SC.sound.play();
is_playing = true;
console.log(is_playing);
}else if(is_playing === true){
SC.sound.pause();
is_playing = false;
console.log(is_playing);
}
});
}
$('body').on("click", ".SCbtn", function(){
var theTrack = $(this).attr('id');
trackCont(theTrack);
});
Update
My Fiddle
回答1:
I think you're overcomplicating things. Here's a simple example:
HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
<button id="play">Play</button>
JavaScript:
SC.initialize({
client_id: 'XXXX'
});
var myPlayer;
var isPaused = false;
SC.stream('tracks/43377447').then(function(player){
player.play()
myPlayer = player;
});
document.querySelector('button').addEventListener('click', function() {
if (isPaused) {
myPlayer.play()
isPaused = false;
} else {
myPlayer.pause()
isPaused = true;
}
});
Working JSFiddle.
回答2:
You should use the toggle() method provided by Soundcloud for easiest implementation. See here: https://developers.soundcloud.com/docs/api/html5-widget
Something like the below should do the trick:
var sc = SC.Widget(iframe);
$('body').on("click", ".SCbtn", function(){
sc.toggle();
});
来源:https://stackoverflow.com/questions/34833048/soundcloud-javascript-sdk-sound-not-pausing