Búsqueda de sitios web

typescript - ¿Cómo usar webrtc en Angular 2?


Intenté usar webrtc en Angular 2 con TypeScript y obtengo el error: navigation.getUserMedia no es una función.

Este es mi código: [

ngOnInit(): void {
    navigator.getUserMedia(this.constraints,
      stream => {
        var track: MediaStreamTrack = stream.getTracks()[0];
        console.log('label:' + track.label);
        console.log('ended:' + track.readyState);
        track.onended = (event:Event) => console.log('Track ended');
        var objectUrl = URL.createObjectURL(stream);
      },
      error => {
        console.log('Error message: ' + error.message);
        console.log('Error name: ' + error.name);
      });
  }

] Código de Plunker

¿Puede alguien ayudarme?

Respuesta #1

Deberías incluir adapter.js: https://github.com/webrtc/adapter

Básicamente, podrías simplemente usar el código de otra respuesta:

navigator.getUserMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

Aunque, hay incluso más funciones de WebRTC que seguirían siendo inaccesibles en ese caso. Por lo tanto, incluir adapter.js es una manera más correcta. Además, es mantenido y actualizado por Google (uno de los mayores contribuyentes de WebRTC).

Respuesta #2

lo siguiente es cómo utilicé webrtc en Angular 4 -->

import {Component, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  @ViewChild('hardwareVideo') hardwareVideo: any;

  _navigator = <any> navigator;
  localStream;

  ngOnInit() {

    const video = this.hardwareVideo.nativeElement;
    this._navigator = <any>navigator;

    this._navigator.getUserMedia = ( this._navigator.getUserMedia || this._navigator.webkitGetUserMedia
    || this._navigator.mozGetUserMedia || this._navigator.msGetUserMedia );

    this._navigator.mediaDevices.getUserMedia({video: true})
      .then((stream) => {
        this.localStream = stream;
        video.src = window.URL.createObjectURL(stream);
        video.play();
    });

  }

  stopStream() {
    const tracks = this.localStream.getTracks();
    tracks.forEach((track) => {
      track.stop();
    });
  }

}

plantilla:

<div style="text-align:center">
  <h1>
    Welcome to my webRTC demo app!
  </h1>
  <button (click)="stopStream()">Stop Streaming</button>
  <video #hardwareVideo autoplay></video>
</div>

Artículos relacionados