I'm creating a push to talk functionality in my vue app. I'm using MediaRecorder API to capture the video based on when the button is pushed and stop capturing when it is released. The functionality is working fine with taking the mouseup and mousedown events and saving the audio. The only issue is synchronization with the recordings saved. For example - If I record first time, the audio recording saved is always zero bytes. For the second speech, the audio recording saved has the content/audio of first time, and it goes on like this.
Not sure what I'm doing wrong. If there's any recommendation for audio capture libraries, please let me know.
<template>
<div class="button">
<ButtonIcon
symbol="mic"
@mousedown="startCapturing"
@mouseup="stopCapturing"
/>
</div>
</template>
startCapturing() {
console.log("Mousedown event")
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
// Stop the current recorder if it's active
this.mediaRecorder.stop();
}
navigator.mediaDevices.getUserMedia({ audio: true })
.then((stream) => {
const recorder = new MediaRecorder(stream)
recorder.addEventListener('dataavailable', (event) => {
this.recordedChunks.push(event.data)
})
recorder.start()
this.mediaRecorder = recorder
})
.catch((error) => {
console.error('Error accessing microphone:', error)
})
},
stopCapturing() {
console.log("Mouseup event");
this.mediaRecorder.addEventListener('stop', () => {
const blob = new Blob(this.recordedChunks);
saveAs(blob, 'recorded-audio.wav');
// Clear the recorded chunks for the next recording
this.recordedChunks = [];
});
this.mediaRecorder.stop();
this.mediaRecorder = null;
},