安排网络音频 Api 播放,多次播放问题

Scheduling Web Audio Api playback, multiple plays issue

我正在尝试将哔声设置为每隔一秒播放 3 次。但是,声音只播放一次。关于为什么会这样的任何想法? (它包含在一个更大的 javascript 函数中,该函数声明上下文等。。)

var beepBuffer;

var loadBeep = function() {  
 var getSound = new XMLHttpRequest(); // Load the Sound with XMLHttpRequest
 getSound.open("GET", "/static/music/chime.wav", true); // Path to Audio File
 getSound.responseType = "arraybuffer"; // Read as Binary Data
 getSound.onload = function() {
  context.decodeAudioData(getSound.response, function(buffer){
   beepBuffer = buffer; // Decode the Audio Data and Store it in a Variable
  });
 }
 getSound.send(); // Send the Request and Load the File
}

var playBeep = function() {
 for (var j = 0;j<3;j++) {
  var beeper = context.createBufferSource(); // Declare a New Sound
  beeper.buffer = beepBuffer; // Attatch our Audio Data as it's Buffer
  beeper.connect(context.destination);  // Link the Sound to the Output
  console.log(j);
  beeper.start(j); // Play the Sound Immediately
}
};

您的代码假定 beeper.start(j) 是一种同步方法,即等待声音播放完毕。情况并非如此,因此您的循环可能几乎同时播放所有 3 个实例。

一种解决方案是通过将时间参数传递给 start() 方法来延迟每个实例的播放:

var numSecondsInBeep = 3;
for (var j = 0; j < 3; j++) {
    var beeper = context.createBufferSource(); // Declare a New Sound
    beeper.buffer = beepBuffer; // Attatch our Audio Data as it's Buffer
    beeper.connect(context.destination); // Link the Sound to the Output
    console.log(j);
    beeper.start(context.currentTime + j * numSecondsInBeep);
}

See here 有关 play() API 的更多信息。

关闭 - 另一个答案的代码将起作用 - 但这不是同步性,而是你没有问 context.current 时间到开始时间。 Start() 不会从 "now" 开始偏移 - 它需要绝对时间。将 context.currentTime 添加到 start 参数,你应该没问题。