DEV Community

Felice Forby
Felice Forby

Posted on

24 3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay