Angular 2 and instantiation of a camera stream with html 5 video

一笑奈何 提交于 2020-01-31 19:34:11

问题


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



来源:https://stackoverflow.com/questions/40131772/angular-2-and-instantiation-of-a-camera-stream-with-html-5-video

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!