angularwebcam

Angular video from user webcam using navigator.mediaDevices.getUserMedia


I am trying to get a video running from the user webcam using navigator.mediaDevices.getUserMedia with video element. I want to capture the image from webcam and make an image file. But I got stuck on getting the webcam to the video element. Here is the html :

<button (click)="startCamera()">Get access to camera</button> 
<div style="width: 640px; height: 480px; border: 1px solid black;">
    <video id="videoC" #videoC height="480px" width="640px" autoplay="true" loop="true" muted="true"></video>
</div>

And here is my .ts file :

@ViewChild("videoC")
videoC! : HTMLVideoElement;

sync startCamera(){

console.log(navigator.mediaDevices.enumerateDevices());

await navigator.mediaDevices.getUserMedia({
  video: {
    aspectRatio: 1.33,
    frameRate: 60,
    width: 640,
    height: 480
  },
  audio: false
}).then((stream) =>{
  this.videoC.srcObject = new MediaStream(stream.getTracks());
  this.videoC.play;
})
.catch((err) => {
  console.error(`An error occurred: ${err}`);
});
console.log(this.videoC);
console.log('Video run');
}

Solution

  • I change the HTMLVideoElement for videoC to ElementRef and it works. Here is the change:

    @ViewChild("videoC")
    videoC! : ElementRef;
    

    And some changes on startCamera() on the this.videoC part. Here it is:

      this.videoC.nativeElement.srcObject = stream;
      this.videoC.nativeElement.play;
    

    Here is the reference where I got the answer from. Webcam access with Angular