'Is there a way to remove pre-start buffer from the MediaRecorder?
I am using MediaRecorder to record microphone input in a web application.
Based on some testing with Chrome v100, the recorded audio contains about 100ms of data from before the MediaRecorder.start() function is called. I determined this by calling .start() in the event handler for a click event on a button. In the resulting audio file, the mouse click is audible. I believe this should be impossible if the recorder does not record data until after the click event is fired.
Here's the resulting audio file in Audacity. The first waveform is the release of the mouse button, and the second is a pure 440Hz tone that is triggered by the same click event.
Is there a way to either remove this pre-.start() portion of the audio file or know how long it is? My application requires that the audio file is synced as closely as possible to the actual start event.
Here's the code that I used for this test, and here's a live version on GitHub Pages
<!DOCTYPE html>
<html>
<head> </head>
<body>
<button id="setup">Setup</button>
<button id="start" disabled>Start Recording</button>
<div id="audio"></div>
</body>
<script>
let audioContext;
let stream;
let recorder;
const recorded_chunks = [];
async function getRecorder() {
audioContext = new AudioContext();
stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: false,
});
recorder = new MediaRecorder(stream);
recorder.addEventListener("start", handleRecorderStart);
recorder.addEventListener("stop", handleRecorderStop);
recorder.addEventListener("dataavailable", handleDataAvailable);
}
function handleRecorderStart(){
setTimeout(stopRecording, 1500);
};
function handleDataAvailable(e){
if (e.data.size > 0) {
recorded_chunks.push(e.data);
}
}
function handleRecorderStop(){
const data = new Blob(recorded_chunks, { type: "audio/webm" });
const audio_url = URL.createObjectURL(data);
document.querySelector("#audio").innerHTML = `<p><audio id="playback" src="${audio_url}" controls></audio></p>`
}
function playTone() {
const note = audioContext.createOscillator();
note.frequency.value = 440;
note.connect(audioContext.destination);
note.start(audioContext.currentTime);
note.stop(audioContext.currentTime + 1);
}
function startRecording() {
recorder.start();
}
function stopRecording() {
recorder.stop();
}
document.querySelector("#setup").addEventListener("click", () => {
getRecorder();
document.querySelector("#start").disabled = false;
});
document.querySelector("#start").addEventListener("click", () => {
playTone();
startRecording();
});
</script>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

