In order to record audio from a user's microphone, we must first gain permission from the user to access the device:
navigator.mediaDevices.getUserMedia({ audio: true })
.then(successCallback)
.catch(failureCallback);
On success, our successCallback
will be called with a MediaStream
object which we can use to access the microphone:
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create a source from our MediaStream
var source = audioContext.createMediaStreamSource(mediaStream);
// Now create a Javascript processing node with the following parameters:
// 4096 = bufferSize (See notes below)
// 2 = numberOfInputChannels (i.e. Stereo input)
// 2 = numberOfOutputChannels (i.e. Stereo output)
var node = audioContext.createScriptProcessor(4096, 2, 2);
node.onaudioprocess = function(data) {
console.log(data);
}
// Connect the microphone to the script processor
source.connect(node);
node.connect(audioContext.destination);
The onaudioprocess
event gives us access to the Raw PCM data stream from the microphone. We can access the buffered data like so:
node.onaudioprocess = function(data) {
var leftChannel = data.inputBuffer.getChannelData(0).buffer;
var rightChannel = data.inputBuffer.getChannelData(1).buffer;
}
When we're finished recording, we must disconnect from the source and discard the script processor:
node.disconnect();
source.disconnect();
Important Notes about bufferSize
The bufferSize
determines how frequently the onaudioprocess
callback is called. Lower values result in lower (better) latency, higher values will reduce audio breakup/glitches. A value of zero will allow the browser implementation to choose an appropriate value. If passed in manually, it must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384.