In audio, to mix two audio streams (here, buffers) into one, you can simply add each sample value together. Practically here we can do this based on your fragment:
function mix(buffers) { 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 * maxDuration, context.sampleRate); for (var j = 0; j < buffers.length; j++) { for (var srcChannel = 0; srcChannel < buffers[j].numberOfChannels; srcChannel++) { var out = mixed.getChanneData(srcChannel); var in = buffers[i].getChanneData(srcChannel); for (var i = 0; i < in.length; i++) { out[i] += in[i]; } } } return out; }
Then just apply the return from this function to the new AudioBufferSourceNode.buffer and play it as usual.
A few notes: my snipp assumes, for simplicity, that:
- If you have a mono buffer and a stereo buffer, you will only hear the mono buffer in the left channel of the mixed buffer. If you want it to be copied left and right, you will need to do this, we call up-mixing;
- If you want the buffer to be quieter or louder than another buffer (for example, if you moved the fader on the mixing console), simply multiply the value of
toMix[i] by a number less than 1.0 to make it quiter, more than 1.0 to make it louder .
And again, the web audio API does all this for you, so I wonder why you need to do this yourself, but at least now you know how :-).
padenot
source share