I want to record some audio using javascript. I found some explanations, but it doesn’t work for me. As far as I understood my code below, stop
should trigger addEventListener('dataavailable' ...
. But as far as I can tell, this code is never executed. Could someone tell me what I have to change that the eventlistener
is being executed?
var demo = document.getElementById("demo")
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
let media_recorder
let audioChunks = []
// https://developers.deepgram.com/docs/getting-started-with-pre-recorded-audio
// https://www.tutorialspoint.com/how-to-record-and-play-audio-in-javascript
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
demo.innerHTML += "demo"
// https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/dataavailable_event
media_recorder = new MediaRecorder(stream);
media_recorder.addEventListener('dataavailable', e => {
audioChunks = []
audioChunks.push(e.data);
});
startButton.addEventListener('click', () => {
// audioChunks = [];
media_recorder.start();
demo.innerHTML += 'Recording started! Speak now.';
});
stopButton.onclick = () => {
media_recorder.stop();
demo.innerHTML += "stop "
audioChunks = []
demo.innerHTML += "Recording stoped!"
};
}).catch (err => {
demo.innerHTML += err
})
2
Answers
You have to put in media_recorder a number of millisecond after whose collecting audio data, for example
media_recorder.start(200);
I think clearing
audioChunks
unnecessarily caused this issue. Here is my try; I hope it helps. I also implemented an audio control to show it’s working, though it doesn’t work due to security reasons on Stack Overflow you should try in you own local host