I'm trying to record a user's voice in the browser using Web API Media Recorder.
At this stage, all I'm trying to do with the audio once recorded is add it to the source of an audio element and play it back.
When I stop the recorder, the 'ondataavailable' event is triggered, but the size of the data is 0, and nothing can be played back.
Here's where my code is at. I'm using React. Any ideas would be very much appreciated!
handleRecording (stream) {
const recordedChunks = this.state.recordedChunks;
const mediaRecorder = new MediaRecorder(stream)
const _this = this;
mediaRecorder.start();
mediaRecorder.ondataavailable = function(e) {
if (e.data.size > 0){
recordedChunks.push(e.data);
_this.setState({recordedChunks:recordedChunks});
}
}
mediaRecorder.onstop = function(e) {
if (recordedChunks){
if(recordedChunks.length > 0) {
const audio = document.querySelector('audio');
audio.controls = true;
const blob = new Blob(recordedChunks, { 'type' : 'audio/ogg; codecs=opus' });
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
}
}
}
this.setState({mediaRecorder:mediaRecorder});
},
startRecording () {
const recording = true;
this.setState({recording:recording});
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(this.handleRecording);
},
stopRecording () {
const recording = false;
const mediaRecorder = this.state.mediaRecorder;
mediaRecorder.stop();
this.setState({recording:recording, mediaRecorder:mediaRecorder});
}
Link to documentation: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/ondataavailable