From b32f2606e7a11bcd217dfa50ac8eb99b04ed68e4 Mon Sep 17 00:00:00 2001 From: Yotam Mann Date: Sun, 19 Feb 2017 11:52:04 -0500 Subject: [PATCH] convert the buffer to mono replaces the existing buffer --- Tone/core/Buffer.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tone/core/Buffer.js b/Tone/core/Buffer.js index 7bb5caf0..3806ffeb 100644 --- a/Tone/core/Buffer.js +++ b/Tone/core/Buffer.js @@ -244,6 +244,32 @@ define(["Tone/core/Tone", "Tone/core/Emitter", "Tone/type/Type"], function(Tone) return this; }; + /** + * Sums muliple channels into 1 channel + * @param {Number=} channel Optionally only copy a single channel from the array. + * @return {Array} + */ + Tone.Buffer.prototype.toMono = function(chanNum){ + if (this.isNumber(chanNum)){ + this.fromArray(this.toArray(chanNum)); + } else { + var outputArray = new Float32Array(this.length); + var numChannels = this.numberOfChannels; + for (var channel = 0; channel < numChannels; channel++){ + var channelArray = this.toArray(channel); + for (var i = 0; i < channelArray.length; i++){ + outputArray[i] += channelArray[i]; + } + } + //divide by the number of channels + outputArray = outputArray.map(function(sample){ + return sample / numChannels; + }); + this.fromArray(outputArray); + } + return this; + }; + /** * Get the buffer as an array. Single channel buffers will return a 1-dimensional * Float32Array, and multichannel buffers will return multidimensional arrays.