Mute and disable video action

I’m trying to add action to webrtc like mute and disable action

  • this action to toggle camera
const toggleCamera = useCallback(async () => {
    if (!isVideoEnabled) {
      const videoSource = (await mediaDevices.enumerateDevices()).find(
        info => info.kind === 'videoinput' && info.facing === 'front',
      );
      if (videoSource) {
        const videoStream = await mediaDevices.getUserMedia({
          audio: false,
          video: {
            mandatory: {
              minWidth: 500,
              minHeight: 300,
              minFrameRate: 30,
            },
            facingMode: 'user',
            optional: videoSource?.id ? [{sourceId: videoSource.id}] : [],
          },
        });
        const videoTracks = videoStream.getVideoTracks();
        localStream.addTrack(videoTracks[0]);
      }
    } else if (!isMuted) {
      const tracks = localStream.getTracks();
      if (tracks.length > 0) {
        tracks.forEach(element => {
          if (element.kind === 'video') {
            element.enabled = !isVideoEnabled;
            IncallManager.setMicrophoneMute(!isMuted);
            setIsVideoEnabled(_isEnabled => !_isEnabled);
          }
        });
      }
    }
  }, [isMuted, isVideoEnabled, localStream]);
  • this action for mute audio
const onMute = useCallback(async () => {
    if (isMuted) {
      const audioStream = await mediaDevices.getUserMedia({
        audio: true,
        video: false,
      });
      const audioTracks = await audioStream.getAudioTracks();
      localStream.addTrack(audioTracks[0]);
    } else if (isVideoEnabled) {
      const tracks = localStream.getTracks();
      if (tracks.length > 0) {
        tracks.forEach(element => {
          if (element.kind === 'audio') {
            element.enabled = !isMuted;
            IncallManager.setMicrophoneMute(!isMuted);
            setIsMuted(_isMuted => !_isMuted);
          }
        });
      }
    }
  }, [isMuted, isVideoEnabled, localStream]);

is that okay or I’m doing something wrong?

Put the getUserMedia call into its own hook that doesn’t depend on isMuted. This hook should store the resulting MediaStreamTrack into state somewhere.

Then, have another hook that looks like:

  useEffect(() => {
    if (track != null) {
      track.enabled = !isMuted;
    }
  }, [track, isMuted]);

I wouldn’t bother with IncallManager.setMicrophoneMute