对于音乐应用程序,我需要能够使用 Web 音频 API 连续无缝地生成原始音频样本。经过搜索,我发现了 AudioBuffer(https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer),看来这就是我需要的。但是,音频缓冲区只能播放一次(https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode),因此不能真正连续播放。我尝试了这种解决方法:
const buffer = audioCtx.createBuffer(1, 10000, audioCtx.sampleRate);
for(let i = 0; i < buffer.length; i++)
buffer.getChannelData(0)[i] = ((i / audioCtx.sampleRate) * 440) % 1;
const source = audioCtx.createBufferSource();
source.buffer = buffer;
source.onended = function() {
console.log(this);
const newSource = audioCtx.createBufferSource();
for(let i = 0; i < buffer.length; i++)
buffer.getChannelData(0)[i] = ((i / audioCtx.sampleRate) * 440) % 1;
newSource.buffer = buffer;
newSource.connect(audioCtx.destination);
newSource.onended = (this.onended as Function).bind(newSource);
newSource.start();
}
source.connect(audioCtx.destination);
source.start();
本质上,这段代码创建了一个缓冲区和源节点,播放缓冲区,当缓冲区结束时,它创建一个新的源和缓冲区并继续播放。但是,当缓冲区完成播放时,此方法会产生明显的静音。我认为这与 JS 事件循环有关,但我不确定。
理想情况下,我想要这样的东西:
audioCtx.createSampleStream(() => {
// generate samples here.
return Math.random() * 2 - 1;
})
希望我能够让它发挥作用。如果我不这样做,我可能会尝试编写一个带有 c++ 绑定的 npm 包来执行此操作。