4

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

zero_cool
  • 3,960
  • 5
  • 39
  • 54
Zain Sahi
  • 123
  • 8

1 Answers1

3

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.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • Is there a way to start the same media stream that is stopped. I have found that there is no method like track.start() – Zain Sahi Apr 12 '22 at 19:18
  • I have tried this approach and it does not work. Why on earth is this so complicated? – zero_cool Apr 20 '23 at 01:21
  • @zero_cool without seeing your code we can't help you. Feel free to open a new question with a proper [mre], and which explain what you've tried and how it failed. – Kaiido Apr 20 '23 at 01:26
  • It's literally the same exact thing. Just curious if any one has found a solution that works. – zero_cool Apr 20 '23 at 16:40
  • @zero_cool well this answer worked for OP. You certainly are missing something. Please post a new question with your code in a way we can reproduce the issue. – Kaiido Apr 20 '23 at 23:05
  • @zero_cool: My experience is that the works fine except in Safari. Maybe that's the issue? – Jan Aagaard Apr 25 '23 at 11:06