I browsed other question like this, but couldn’t find any working solutions.
When I want to access a videodevice I get a DOMException error and in other questions the answers were to stop the previous stream, but I already do.
In my angular project before calling the navigator.mediaDevices.getUserMedia I stop the last stream like this:
private async stopCurrentStream(): Promise<void> {
return new Promise<void>((resolve) => {
this.video.nativeElement.pause();
this.video.nativeElement.srcObject = null;
this.video.nativeElement.src = null;
if (!this.stream) resolve();
this.stream.getTracks().forEach((track: MediaStreamTrack) => {
track.stop();
this.stream.removeTrack(track);
});
this.stream = null;
resolve();
});
}
And this is how I want to start a video stream:
private async startVideo(
deviceId: string = this.videoDevices[0]?.deviceId
): Promise<void> {
console.log('start vid', deviceId);
navigator.mediaDevices
.getUserMedia({
video: {
deviceId: {exact: deviceId}
},
})
.then((stream: MediaStream) => {
console.log('then', stream);
this.stream = stream;
this.video.nativeElement.srcObject = stream;
this.video.nativeElement.play();
})
.catch((err) => {
console.log('Error accessing the camera with id', err);
});
}
The strange thing I only get this error if I’d like to access a specific camera, if I remove the device id it always works. However I’d like to be able to switch between cameras.
Also if I loop the startVideo function until it succeeds, after 20-100 retries later it manages to access the camera. I tried setting a timeout between stopping and starting a video stream, but no success.
2