I am creating an app where user can record and play there video. I am doing it in same video tag to stream and play the recorded video but I am having issue when I start the recording thrid time. For th first time when I start record and stop then play the video its works fine and when do again it works fine but when so it one more time the media stream stop and I get error DOMException: Failed to execute 'start' on 'MediaRecorder': There was an error starting the MediaRecorder. I am not able to understand why its not working on third time. Please if someone can help me out finding the issue.
This is my code.
Start Camera
startCamera(): void {
this.videoElement.play();
navigator.mediaDevices
.getUserMedia({
video: true,
audio: {
echoCancellation: {exact: true}
},
})
.then((stream) => {
this.videoStream = stream;
this.addStream();
})
.catch((err) => {
});
}
Adding Stream to video tag
private addStream(): void {
this.videoElement.srcObject = this.videoStream;
}
Start Record record(): void {
if (this.videoElement.srcObject === null) {
this.videoElement.removeAttribute('src')
this.addStream();
this.videoElement.play();
}
const sUsrAg = navigator.userAgent;
if (sUsrAg.indexOf('Firefox') > -1) {
this.videoElement.mozCaptureStream();
this.startRecordingMedia(this.videoElement.mozCaptureStream());
} else {
this.startRecordingMedia(this.videoElement.captureStream());
}
}
private startRecordingMedia(stream: MediaStream): void {
try {
this.recorder = new MediaRecorder(stream);
const data = [];
this.recorder.ondataavailable = (event) => data.push(event.data);
this.recorder.onerror = (event) => {
console.log(event);
};
this.recorder.start();
this.recorder.addEventListener('stop', () => {
console.log('stopped')
});
} catch (e) {
console.log(e)
}
}
Stop Recording
this.videoElement.pause();
this.recorder.stop();
this.videoElement.srcObject = null;
const recordedBlob = new Blob(data);
this.videoElement.src = URL.createObjectURL(recordedBlob);
You need to wait that your <video> actually started playing before recording the MediaStream captured from it. At the time you call MediaRecorder.start(), the this.videoElement.play(); Promise still hasn't resolved, and nothing is in the MediaStream, hence the MediaRecorder can't produce correct data.
So you could simply await that call to play(), but there is absolutely no point in even capturing the MediaStream again from the <video>, instead record directly the MediaStream you have from the camera (stored in this.stream), you'll save trees.