Last active
August 29, 2015 13:56
-
-
Save kevincennis/9041112 to your computer and use it in GitHub Desktop.
Merge buffers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assuming `rec1` and `rec2` are both instances of Recorder... | |
var buf1L, buf1R, buf2L, buf2R, worker, count = 0; | |
// start a new worker | |
// we can't use Recorder directly, since it doesn't support what we're trying to do | |
worker = new Worker('recorderWorker.js'); | |
// initialize the new worker | |
worker.postMessage({ | |
command: 'init', | |
config: {sampleRate: 44100} | |
}); | |
// callback for `exportWAV` | |
worker.onmessage = function( e ) { | |
var blob = e.data; | |
// this is would be your WAV blob | |
}; | |
// get the left and right buffers from `rec1` | |
rec1.getBuffer(function( buffers ) { | |
buf1L = buffers[0]; | |
buf1R = buffers[1]; | |
status(); | |
}); | |
// get the left and right buffers from `rec2` | |
rec2.getBuffer(function( buffers ) { | |
buf2L = buffers[0]; | |
buf2R = buffers[1]; | |
status(); | |
}); | |
// just a simple/hacky way to tell if we've got buffers for | |
// both Recorder instances (should probably be promises/deferreds) | |
function status() { | |
if ( ++count === 2 ) { | |
merge(); | |
} | |
} | |
// figure out the max length across each buffer, then loop | |
// through and sum all the values into two new left and right buffers | |
function merge() { | |
var len, left, right, i = 0; | |
len = Math.max.apply(Math, [buf1L, buf1R, buf2L, buf2R].map(function( buf ) { | |
return buf.length; | |
}); | |
left = new Float32Array(len); | |
right = new Float32Array(len); | |
for ( ; i < len; ++i ) { | |
left[i] = ( buf1L[i] || 0 ) + ( buf2L[i] || 0 ); | |
right[i] = ( buf1R[i] || 0 ) + ( buf2R[i] || 0 ); | |
} | |
record(left, right); | |
} | |
// send the new buffers to the worker, then ask it for a WAV | |
function record( left, right ) { | |
worker.postMessage({ | |
command: 'record', | |
buffer: [left, right] | |
}); | |
// not sure if this is necessary or not, but it doesn't hurt | |
setTimeout(function() { | |
worker.postMessage({ | |
command: 'exportWAV', | |
type: 'audio/wav' | |
}); | |
}, 100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment