javascriptreactjswebrtcmediastream

Webcam light doesnt turn off after setting the video constraint to false in webRtc


I am using WebRTC and socket.io for video calling.

The call is working fine but when I run the turn off camera function, the video stops but the light of my webcam remains on.

Here is the function for turning off the camera:


const mute = () => {
  setMuteCamera(true);
  navigator.mediaDevices
    .getUserMedia({ video: false, audio: true })
    .then((stream) => {
      setStream(stream);
      myVideo.current.srcObject = stream;
      if (stream != null) {
        stream?.getTracks().forEach((track) => {
          track.stop();
        });
      }
    });
};


Solution

  • Every time you call navigator.mediaDevices.getUserMedia() a new MediaStream is created, with new MediaStreamTracks. Closing these new MediaStreamTracks won't close the previous ones.

    So what you need is to keep track of your previous MediaStream, and close the VideoTrack from it.
    Given your current code it seems that you do set it as myVideo.current.srcObject, if so, you can access it from there:

    const muteVideoTrack = () => {
      myVideo.current.srcObject.getVideoTracks().forEach((track) => track.stop());
    };
    

    Or you could also simply store this MediaStream in any variable accessible to your method.
    This will let the MediaStream capture only the microphone. If you wanted to completely stop the whole MediaStream, then call getTracks() instead of getVideoTracks(), and optionally set the srcObject to null.