PeerJS + Angular4 - 如何在流式传输时打开/关闭相机和麦克风

时间:2017-09-02 15:23:39

标签: javascript angular peerjs

我正在使用一些视频通话模块在angular4中制作应用程序。我已经实现了两个模块 - 主机和客户端,他们之间的视频通话工作正常。 现在我想制作一个可以打开和关闭相机和麦克风的两个按钮,就像在skype或环聊等标准通讯器中一样。

如何实现这个?

我会为此展示我的代码,但这不起作用。

HOST:

this.peer = new Peer({key: 'xxxxxxxxxxxxxx'});

setTimeout(() => {
  this.id = this.peer.id;
},3000);


var navig = <any>navigator;
navig.getUserMedia =  ( navig.getUserMedia || navig.webkitGetUserMedia || navig.mozGetUserMedia || navig.msGetUserMedia );

this.peer.on('call', (call) => {
  navig.getUserMedia({video: true, audio: true}, (stream) =>
  {
    this.stream = stream;
    myVideoElement.src=URL.createObjectURL(stream);
    myVideoElement.play();
    call.answer(stream);
    call.on('stream', function(remotestream){
      videoElement.src = URL.createObjectURL(remotestream);
      videoElement.play();
    })
  },(err) => {
    console.log('Failed to get stream', err);
  })
});

HOST func转动麦克风:

switchMicrophone(){

console.log(this.stream);

var navig = <any>navigator;
navig.getUserMedia =  ( navig.getUserMedia || navig.webkitGetUserMedia || navig.mozGetUserMedia || navig.msGetUserMedia );
navig.video = false;

// var track = this.stream.getTracks()[0];
// track.stop();
// track = this.stream.getTracks()[1];
// track.stop();

}

不幸的是,对于某些不为人知的原因,this.stream未定义,其他代码无效。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案。 下面的代码,也许这将有助于某人。享受!

在此示例中,我有两个视频元素 - 一个用于来自客户端的视频,另一个用于仅显示我,作为预览视频

  switchMicrophone(){
    this.isMicrophoneEnabled = !this.isMicrophoneEnabled;
    this.stream.getAudioTracks()[0].enabled = this.isMicrophoneEnabled;
  }

  switchCamera(){
    this.isCameraEnabled = !this.isCameraEnabled;
    this.stream.getVideoTracks()[0].enabled = this.isCameraEnabled;
    this.previewStream.getVideoTracks()[0].enabled = this.isCameraEnabled;
  }


this.navig.getUserMedia({video: true, audio: false}, (stream)=> {
  this.previewStream = stream;
  this.previewVideoElement.nativeElement.src = URL.createObjectURL(stream);
  this.previewVideoElement.nativeElement.play();
}, function(err) {
  console.log('Failed to get stream', err);
});

this.peer.on('call', (call)=> {
  this.navig.getUserMedia({video: true, audio: true}, (stream)=> {
    this.stream = stream;
    call.answer(stream);
    call.on('stream', (remotestream)=>{
      this.videoElement.nativeElement.src = URL.createObjectURL(remotestream);
      this.videoElement.nativeElement.play();
    })
  }, function(err) {
    console.log('Failed to get stream', err);
  })
});