【问题标题】:Scheduling Web Audio Api playback, multiple plays issue调度 Web Audio Api 播放,多次播放问题
【发布时间】:2015-10-04 09:19:57
【问题描述】:

我正在尝试安排蜂鸣声每隔一秒播放 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
}
};

【问题讨论】:

    标签: javascript audio web-audio-api


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您的代码假定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 的更多信息。

      【讨论】:

        猜你喜欢
        • 2018-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 2013-10-16
        • 2014-01-19
        • 2021-07-24
        相关资源
        最近更新 更多