From 08c3a63dc170c5f3154a86566e7b31b133d20cda Mon Sep 17 00:00:00 2001 From: alfred Date: Wed, 1 Jan 2014 00:27:03 +0000 Subject: [PATCH] average mixing --- lib/mixer.js | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/lib/mixer.js b/lib/mixer.js index 497f02f..85dbc8e 100644 --- a/lib/mixer.js +++ b/lib/mixer.js @@ -9,11 +9,27 @@ function Mixer(args) { if (typeof args === 'undefined') args = {}; if (args.channels != 1 && args.channels != 2) args.channels = 2; - if (args.bitDepth != 8 && args.bitDepth != 16 && args.bitDepth != 32) args.bitDepth = 16; if (typeof args.sampleRate === 'number' || args.sampleRate < 1) args.sampleRate = 44100; - this.channels = args.channels; this.bitDepth = args.bitDepth; + if (args.bitDepth == 8) { + this.readSample = Buffer.readInt8; + this.writeSample = Buffer.writeInt8; + this.sampleByteLength = 1; + } + else if (args.bitDepth == 32) { + this.readSample = Buffer.readInt32LE; + this.writeSample = Buffer.writeInt32LE; + this.sampleByteLength = 4; + } + else { + args.bitDepth = 16; + this.readSample = Buffer.readInt16LE; + this.writeSample = Buffer.writeInt16LE; + this.sampleByteLength = 2; + } + + this.channels = args.channels; this.sampleRate = args.sampleRate; this.inputs = []; @@ -22,7 +38,25 @@ function Mixer(args) { util.inherits(Mixer, Readable); Mixer.prototype._read = function() { - this.push(0); + + var samples = 9007199254740992; + this.inputs.forEach(function (input) { + var as = input.availSamples(); + if (as < samples) samples = as; + }); + if (samples > 0) { + + var mixedBuffer = new Buffer(samples * this.sampleByteLength); + for (var i = 0; i < samples; i++) { + var mixedSample = 0; + for (var j = 0; j < this.inputs.length; j++) { + mixedSample += this.inputs[j].readSample.call(this.inputs[j], i * this.inputs[j].sampleByteLength); + } + this.writeSample.call(mixedBuffer, Math.round(mixedSample / this.inputs.length), i * this.sampleByteLength); + } + + this.push(mixedBuffer); + } } Mixer.prototype.input = function (args) {