I've created a basic MediaStream which gets a video & audio track in my react-app like this:
const getLocalStream: MediaStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
setLocalStream(getLocalStream);
const handleShowCamClick = async () => {
if (!callContext.localStream) return;
callContext.localStream.getVideoTracks().forEach((track: MediaStreamTrack) => track.enabled = true);
callContext.setShowCam(true);
};
const handleHideCamClick = () => {
if (!callContext.localStream) return;
// callContext.localStream.getVideoTracks().forEach((track: MediaStreamTrack) => track.enabled = false);
callContext.localStream.getVideoTracks().forEach((track: MediaStreamTrack) => track.stop());
callContext.setShowCam(false);
};
So now I want the user to be able to disable its webcam. Setting track.enabled = false will result in the webcam still being used by the webapp but turning the video to black, which is not the behaviour I want.
Instead I want the webcam to no longer be used by the webapp.
I have a webcam with a blue light shining every time to show that the cam is recording. With track.enabled = false my webcam shows me that its still technically recording.
If I remove the video, track.stop() will result in the behaviour I want. The webcam is no longer used, but I how do I add the video track of the webcam back to the localStream?
track.stop() removes the track from localStream and frees the webcam from the MediaStream, but since the video track is not there anymore, how can I request a new video track of the webcam and attach it to localStream without re-initializing a MediaStream?