How to add audio/video mute/unmute buttons in WebRTC video chat

tagaism picture tagaism · Dec 26, 2015 · Viewed 12.5k times · Source

I'm trying to create WebRTC video chat. Now I'm stacked on creating media-tracks buttons (mute video to enable or disable video sending, and mute audio to make the same with audio). Here is my code.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
  <script type="text/javascript" src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
  <script>
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

  var myStream;
  var peer = new Peer({key: 'PeerJS key'});
  var setOthersStream = function(stream){
    $('#others-video').prop('src', URL.createObjectURL(stream));
  };

  var setMyStream = function(stream){
    myStream = stream;
    $('#video').prop('src', URL.createObjectURL(stream));

  };

  peer.on('open', function(id){
    $('#peer-id').text(id);
  });

  peer.on('call', function(call){
    call.answer(myStream);
    call.on('stream', setOthersStream);
  });

  $(function(){
    navigator.getUserMedia({audio: true, video: true}, setMyStream, function(){});

    $('#call').on('click', function(){
      var call = peer.call($('#others-peer-id').val(), myStream);
      call.on('stream', setOthersStream);
    });
  });

  peer.on('error', function(e){
    console.log(e.message);
  });

Can anyone guide me please?

Answer

jib picture jib · Dec 27, 2015

The video and audio tracks in your stream have an enabled attribute you can modify. E.g.:

function muteMic() {
  myStream.getAudioTracks().forEach(track => track.enabled = !track.enabled);
}

function muteCam() {
  myStream.getVideoTracks().forEach(track => track.enabled = !track.enabled);
}