Reputation: 322
I am building a react app and need to access the webcam which get with the following code:
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(function(stream) {
video.srcObject = stream;
window.localstream = stream;
video.play();
})
However, when I unmount the current component, my webcam stays on. In my componentWillUnmount block, I have tried the following code.
video.pause();
video.srcObject=null;
window.localstream.getTracks()[0].stop();
window.localstream.getVideoTracks()[0].stop();
My webcam light still stays on however. When I console.log the mediaStreamTrack afterwards, I get:
How do I stop my webcam?
Upvotes: 10
Views: 4438
Reputation: 134
This post looks old, for those who have the same problem, try this approach
import * as React from "react";
// in your component
const video = React.useRef();
const tracks = window.localstream.getTracks();
tracks.forEach((track) => {
if (track.kind === "video") {
if (track.enabled) {
track.stop();
track.enabled = false;
}
}
});
video.current.srcObject = null;
Upvotes: 1
Reputation: 91
If you are using multiple cameras, then you need to make sure that your code is trying to "stop" the same camera as you turn on before.
You need to make sure your code only call getUserMedia once, then getVideoTracks()[0].stop() should work fine.
Upvotes: 9