1

我正在尝试使用以下代码切换启动和停止 Sound Cloud 流。play() 方法就像条件逻辑一样工作。但是 stop() 方法不是。谁能解释我做错了什么?

SC.initialize({
  client_id: 'MY_CLIENT_ID'
});

  if (streamingBool) {
      SC.stream("/tracks/" + myTrackId, function (sound1) {
          sound1.stop();
      });
      streamingBool = false;
  } else {
      SC.stream("/tracks/" + myTrackId, function (sound) {
          sound.play();
      });
      streamingBool = true;
  }
4

1 回答 1

0

这段代码有两个问题

  • SC.stream 异步执行其函数回调
  • 可变范围,即您试图停止当前播放的声音以外的声音

一个可行的实现是:

SC.initialize({
  client_id: 'MY_CLIENT_ID'
});

var playing = false;    

// Play a track
play = function(myTrackId){
  if(playing){
    SC.sound.stop();
  }

  SC.stream("/tracks/" + myTrackId, function(sound){
    // Store the sound object inside the SC object which belongs 
    // to the global scope so that it can be accessed out of the 
    // scope of this callback
    SC.sound = sound;
    SC.sound.play();
    playing = true;
  });
}

// Stop the currently playing track
stop = function(){
  if(playing){
    SC.sound.stop();
  }
}
于 2015-04-29T06:56:59.183 回答