且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

覆盖两个音频缓冲到一个缓冲区源

更新时间: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,使其更响亮。

  • 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 copied to the left and right, you will have to do we is called up-mixing ;
  • If you want a buffer to be quieter or louder than another buffer (like if you moved a volume fader on a mixing console), simply multiply the 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 :-).