Search code examples
javascriptgetusermedia

Muting an AudioStreamTrack in JS


I am working with getUserMedia(), which returns a MediaStream containing an AudioStreamTrack. How can I mute the AudioStreamTrack? It has a onmute event so it should be somehow able to mute the track.


Solution

  • Use track.enabled (https fiddle for Chrome):

    navigator.mediaDevices.getUserMedia({audio: true})
      .then(stream => audio.srcObject = stream)
      .catch(e => console.log(e));
    
    mute.onclick = () => { audio.srcObject.getTracks()[0].enabled = !mute.checked; };
    <audio id="audio" controls autoplay></audio>
    <label><input type="checkbox" id="mute">mute</label>
    <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

    Note that onmute doesn't fire in this case. It only fires if the mic is muted outside the control of JavaScript, e.g. by an end-user (although no browser implements that yet).