Sound Cloud javascript API Stop()方法不工作

Sound Cloud javascript API Stop() method not working

本文关键字:方法 工作 Stop Cloud javascript API Sound      更新时间:2023-09-26

我正在尝试切换启动和停止声音云流与以下代码。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;
  }

这段代码有两个问题

  • SC。流异步执行回调函数
  • 变量作用域,即您正在尝试停止当前播放的声音以外的声音

一个可行的实现是:

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();
  }
}