DEV Community

Felice Forby
Felice Forby

Posted on

Stopping a Webcam with JavaScript

I recently had to manually get a running web camera to turn off using JavaScript for a project at work.

I had a hard time figuring out JavaScript's MediaStream API so here are some quick notes on how I got the camera to stop.

If the camera is running through a video element, you can stop the video by getting its MediaStreamTrack object and using the stop() method:

const video = document.querySelector('video');

// A video's MediaStream object is available through its srcObject attribute
const mediaStream = video.srcObject;

// Through the MediaStream, you can get the MediaStreamTracks with getTracks():
const tracks = mediaStream.getTracks();

// Tracks are returned as an array, so if you know you only have one, you can stop it with: 
tracks[0].stop();

// Or stop all like so:
tracks.forEach(track => track.stop())
Enter fullscreen mode Exit fullscreen mode

Another way to get all the MediaStreams is to use mediaDevices.getUserMedia() which is called on navigator tracks. It prompts the user for permission (if not already granted) to access the media devices. It will return a Promise so you can write the necessary code within the Promise's then:

navigator.mediaDevices.getUserMedia({video: true, audio: false})
  .then(mediaStream => {
    const stream = mediaStream;
    const tracks = stream.getTracks();

    tracks[0].stop;
  })
Enter fullscreen mode Exit fullscreen mode

Make sure you only call getUserMedia once or stop() won't work, so if your code or a library you're using calls getUserMedia on the page to activate a camera, then you probably won't be able to use this method.

References

Oldest comments (0)