WebRTC: Is it possible to control the microphone and volume levels

后端 未结 2 359
时光说笑
时光说笑 2020-12-16 04:21

I am working on a demo site which includes a slide-out widget that allows a user to place a call.

I am using the SIPml5 tool along with the webrtc2sip back end for h

相关标签:
2条回答
  • 2020-12-16 04:36

    Well it is possible, but currently only in Chrome and with some assumptions. I am not the auther, you can find inspiration for this code in this open-source library (SimpleWebRtc).

    navigator.webkitGetUserMedia(constraints, 
        function(webRTCStream){
            var context = new window.AudioContext();
            var microphone = context.createMediaStreamSource(webRTCStream);
            var gainFilter = context.createGain();
            var destination = context.createMediaStreamDestination();
            var outputStream = destination.stream;
            microphone.connect(gainFilter);
            gainFilter.connect(destination);
            var filteredTrack = outputStream.getAudioTracks()[0];
            webRTCStream.addTrack(filteredTrack);
            var originalTrack = webRTCStream.getAudioTracks()[0];
            webRTCStream.removeTrack(originalTrack);
        },
        function(err) {
            console.log("The following error occured: " + err);
          }
     );
    

    The trick is to modify the stream and then replace the audio track of current stream with audio track of modified stream (taken from MediaStreamDestination stream).

    DISCLAIMER:

    This doesn't work in FireFox as of version 35, since they merely didn't implement MediaStream.addTrack/removeTrack. I use this check currently

      this.micVolumeIsSupported = function() {
        var MediaStream = window.webkitMediaStream || window.MediaStream;
        return !!MediaStream.prototype.addTrack && !!MediaStream.prototype.removeTrack;
      };
    _gainSupported = this.micVolumeIsSupported();
    

    This has a limitation in Chrome due to a bug with stopping stream with mixed up tracks. You might wish to restore these tracks before closing connection or on connection interruption;

    this.restoreTracks = function(){
      if(_gainSupported && _tracksSubstituted){
        webRTCStream.addTrack(originalTrack);
        webRTCStream.removeTrack(filteredTrack);
        _tracksSubstituted = false;
      }
    };
    

    This works for me

    0 讨论(0)
  • 2020-12-16 04:37

    Afaik it's impossible to adjust microphone volume. But you can switch it on/off by using stream api:

    function toggleMic(stream) { // stream is your local WebRTC stream
      var audioTracks = stream.getAudioTracks();
      for (var i = 0, l = audioTracks.length; i < l; i++) {
        audioTracks[i].enabled = !audioTracks[i].enabled;
      }
    }
    

    This code is for native webrtc api, not sipML5. It seems they haven't implemented it yet. Here is not so clear receipt for it.

    0 讨论(0)
提交回复
热议问题