Sometimes, we want o stop or close webcam stream which is opened by navigator.mediaDevices.getUserMedia with JavaScript.
In this article, we’ll look at how to stop or close webcam stream which is opened by navigator.mediaDevices.getUserMedia with JavaScript.
How to stop or close webcam stream which is opened by navigator.mediaDevices.getUserMedia with JavaScript?
To stop or close webcam stream which is opened by navigator.mediaDevices.getUserMedia with JavaScript, we call stop
on each track.
For instance, we write
const stream = await navigator.mediaDevices.getUserMedia({
/* ... */
});
stream.getTracks().forEach((track) => {
track.stop();
});
to use navigator.mediaDevices.getUserMedia
to get a stream
.
Then we call getTracks
to get the tracks.
Next, we call forEach
to loop through each track
and call stop
to stop it.
Conclusion
To stop or close webcam stream which is opened by navigator.mediaDevices.getUserMedia with JavaScript, we call stop
on each track.