PeerJS + Angular4 - how to turn on/off camera and microphone while streaming

1.2k views Asked by At

I am making app in angular4 with some video call module. I have implemented two module - host and client, and video call between theirs is working fine. Now I want to make a two buttons that would turning on and off camera and microphone, as usually in standard comunicators like skype or hangout.

How implement this?

I will show my code for this, but this is no working.

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 to turn of microphone:

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();

}

Unfortunately this.stream is undefined for some unknown for me reason, other code don't working. What should I do?

1

There are 1 answers

0
Maciej Wojcik On

I found answer for my problem. Code below, maybe this will help someone. Enjoy!

In this example I have two video elements - one for video from client, and one to display only me, as a preview video

  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);
  })
});