From 86de2c2d30aece35fb81b1d8f72ecbf34e7c84b7 Mon Sep 17 00:00:00 2001 From: Chris Wilson Date: Mon, 19 Nov 2012 12:55:05 -0600 Subject: [PATCH] Fixed getBuffer() by maintaining separate L and R channels. Interleaves buffer only to export WAV. --- README.md | 16 +++++++++++++++- recorderWorker.js | 26 +++++++++++++++----------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 50ff9f20..a38025a6 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,21 @@ In addition, you may specify the type of Blob to be returned (defaults to 'audio rec.getBuffer([callback]) -This will pass the recorded buffer (as a Float32Array) to the callback. It can be played back by creating a new source buffer and setting this as its channel data (i.e. `newSource.buffer.getChannelData(0).set(recordedBuffer)`). +This will pass the recorded stereo buffer (as an array of two Float32Arrays, for the separate left and right channels) to the callback. It can be played back by creating a new source buffer and setting these buffers as the separate channel data: + + function getBufferCallback( buffers ) { + var newSource = audioContext.createBufferSourceNode(); + var newBuffer = audioContext.createBuffer( 2, buffers[0].length, audioContext.sampleRate ); + newBuffer.getChannelData(0).set(buffers[0]); + newBuffer.getChannelData(1).set(buffers[1]); + newSource.buffer = newBuffer; + + newSource.connect( audioContext.destination ); + newSource.start(0); + } + +This sample code will play back the stereo buffer. + rec.configure(config) diff --git a/recorderWorker.js b/recorderWorker.js index 30ed9fe8..c5fa3662 100644 --- a/recorderWorker.js +++ b/recorderWorker.js @@ -1,5 +1,6 @@ var recLength = 0, - recBuffers = [], + recBuffersL = [], + recBuffersR = [], sampleRate; this.onmessage = function(e){ @@ -27,29 +28,32 @@ function init(config){ } function record(inputBuffer){ - var bufferL = inputBuffer[0]; - var bufferR = inputBuffer[1]; - var interleaved = interleave(bufferL, bufferR); - recBuffers.push(interleaved); - recLength += interleaved.length; + recBuffersL.push(inputBuffer[0]); + recBuffersR.push(inputBuffer[1]); + recLength += inputBuffer[0].length; } function exportWAV(type){ - var buffer = mergeBuffers(recBuffers, recLength); - var dataview = encodeWAV(buffer); + var bufferL = mergeBuffers(recBuffersL, recLength); + var bufferR = mergeBuffers(recBuffersR, recLength); + var interleaved = interleave(bufferL, bufferR); + var dataview = encodeWAV(interleaved); var audioBlob = new Blob([dataview], { type: type }); this.postMessage(audioBlob); } function getBuffer() { - var buffer = mergeBuffers(recBuffers, recLength) - this.postMessage(buffer); + var buffers = []; + buffers.push( mergeBuffers(recBuffersL, recLength) ); + buffers.push( mergeBuffers(recBuffersR, recLength) ); + this.postMessage(buffers); } function clear(){ recLength = 0; - recBuffers = []; + recBuffersL = []; + recBuffersR = []; } function mergeBuffers(recBuffers, recLength){