Angular 2 and instantiation of a camera stream wit

2020-06-25 06:42发布

问题:

I'm new to Angular 2.

If I have a video tag, like :

<video width="480" height="480" autoplay></video>    

And a javascript example snippet to open the camera stream :

var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
  });
}

In Angular 2 + Typescript I suppose I can access the video tag like :

@Component({
  selector: 'video-component',
  template: `
    <video #videoplayer autoplay></video>
  `
})
export class Video {
 @ViewChild('videoplayer') videoPlayer;
  ngAfterViewInit() {
    let video = document.getElementById('video');

    // How to access the mediadevice ??

  }
}

How can I access the media device and instantiate the stream like illustrated in the javascript snippet ?

回答1:

In your template you can include the video directive like this:

<video #video width="640" height="480" autoplay></video>

then in your component:

@ViewChild('video') video:any; 
// note that "#video" is the name of the template variable in the video element

ngAfterViewInit() {
  let _video=this.video.nativeElement;
  if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true })
                          .then(stream => {
                            _video.src = window.URL.createObjectURL(stream);
                            _video.play();
                          })
  }
}

see this on stackblitz: https://stackblitz.com/edit/live-video