Skip to content

Instantly share code, notes, and snippets.

@dulichan
Created October 19, 2016 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dulichan/54c1edc7ce789c67c73e1260f036bb87 to your computer and use it in GitHub Desktop.
Save dulichan/54c1edc7ce789c67c73e1260f036bb87 to your computer and use it in GitHub Desktop.
Recording in the Browser
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// Using arrow functions from ES 6
navigator.getUserMedia({ audio: true }, (stream) => {
// API works in a pipe mechanism
const gain = audioContext.createGain();
const audioSource = audioContext.createMediaStreamSource(stream);
// we connect the gain pipe to the audio source pipe.
var gainNode = audioSource.connect(gain);
const bufferSize = 2048;
const recorder = audioContext.createScriptProcessor(bufferSize, 2, 2);
// Script processor allows a function to execute once a certain buffer range is captured from the API.
// This is another pipe
recorder.onaudioprocess = (event) => {
for(let i = 0; i < 2; i++) {
// Typed array is used to hold the ArrayBuffer that is returned.
const channel = new Float32Array(event.inputBuffer.getChannelData(i));
this.buffers[i].push(channel);
}
this.bufferLength += bufferSize;
};
// We connect the gain pipe to the recorder as well
gain.connect(recorder);
// Recorder pipe is then connected to the audioContext. Audio Context will then push the bytes to the recorder pipe.
recorder.connect(audioContext.destination);
this.recordingStream = stream;
}, (err) => {
console.error(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment