更新时间:2023-11-08 21:57:10
在音频,为的混合的两个音频流(在这里,缓冲区)合并为一个,你可以简单地添加每个采样值在一起。实际上,这是我们能够做到这一点,建立在你的代码片段:
In audio, to mix two audio stream (here, buffers) into one, you can simply add each sample value together. Practically, here is we can do this, building on your snippet:
/* `buffers` is a javascript array containing all the buffers you want
* to mix. */
function mix(buffers) {
/* Get the maximum length and maximum number of channels accros all buffers, so we can
* allocate an AudioBuffer of the right size. */
var maxChannels = 0;
var maxDuration = 0;
for (var i = 0; i < buffers.length; i++) {
if (buffers[i].numberOfChannels > maxChannels) {
maxChannels = buffers[i].numberOfChannels;
}
if (buffers[i].duration > maxDuration) {
maxDuration = buffers[i].duration;
}
}
var out = context.createBuffer(maxChannels,
context.sampleRate * maxLength,
context.sampleRate);
for (var j = 0; j < buffers.length; j++) {
for (var srcChannel = 0; srcChannel < buffers[j].numberOfChannels; srcChannel++) {
/* get the channel we will mix into */
var out = mixed.getChanneData(srcChannel);
/* Get the channel we want to mix in */
var in = buffers[i].getChanneData(srcChannel);
for (var i = 0; i < toMix.length; i++) {
out[i] += in[i];
}
}
}
return out;
}
然后,只需影响从这个函数到一个新的 AudioBufferSourceNode.buffer
的回报,并发挥它像往常一样。
Then, simply affect the return from this function to a new AudioBufferSourceNode.buffer
, and play it like usual.
一对夫妇的注意事项:我段假定,为简单起见,即:
A couple notes: my snippet assumes, for simplicity, that:
toMix [I]
由一些比1.0更小的值,使之quiter,大于1.0,使其更响亮。toMix[i]
value by a number lesser than 1.0 to make it quiter, greater than 1.0 to make it louder.话又说回来,网络音频API做一切给你,所以我不知道为什么你需要自己做,但至少现在你知道如何:-)。
Then again, the Web Audio API does all that for you, so I wonder why you need to do it yourself, but at least now you know how :-).