pengcheng95
pengcheng95

Reputation: 322

Webcam Light Stays on Even After I run MediaStreamTrack.stop()

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:

enter image description here

How do I stop my webcam?

Upvotes: 10

Views: 4438

Answers (2)

Muller Roufaou
Muller Roufaou

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

Wei Ni
Wei Ni

Reputation: 91

  1. 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.

  2. You need to make sure your code only call getUserMedia once, then getVideoTracks()[0].stop() should work fine.

Upvotes: 9

Related Questions