'convert recording audio to buffer
I want to record audio in javascript and convert it to a buffer at the time (not saving it to a file and then converting it to a buffer). how I can do this? I tried to do this with Web Audio but I couldn't export any buffer from Audio Context.
Thank you !
Solution 1:[1]
This should do it.
function _getMicrophoneUserMedia() {
if (!navigator.mediaDevices) navigator.mediaDevices =
navigator.webkitMediaDevices || navigator.mozMediaDevices ||
navigator.msMediaDevices;
if (!navigator.mediaDevices) throw Error('Browser does not support mediaDevices.');
return navigator.mediaDevices.getUserMedia({
video: false,
audio: {
echoCancellation: true,
noiseSuppression: true,
},
});
}
function _getBestBufferSize() { // Return 0 unless it's on a browser that has problems in their implementation.
return typeof window.AudioContext === "undefined" ? 4096 : 0;
}
async function startRecording(audioContext, onReceiveAudio) {
const mediaStream = await _getMicrophoneUserMedia();
const bufferSize = _getBestBufferSize();
const inputChannels = 1; // Nearly every mic will be one channel.
const outputChannels = 1; // Chrome is buggy and won't work without this.
// createScriptProcessor() is deprecated, but the AudioWorklet
// solution is more complicated and won't work in Webpack without
// configuration of loaders.
const recorder = context.createScriptProcessor(
bufferSize, inputChannels, outputChannels
);
recorder.connect(context.destination);
const audioInput = context.createMediaStreamSource(mediaStream);
audioInput.connect(recorder);
recorder.onaudioprocess = (e) => {
const samples = e.inputBuffer.getChannelData(0);
if (!samples.length) return;
onReceiveBuffer(e.inputBuffer);
};
}
// Start recording - onReceiveAudio is a callback you've defined.
const audioContext = new AudioContext(); // It's good to pool and reuse.
startRecording(audioContext, onReceiveAudio);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Erik Hermansen |