Search code examples
javascriptgetusermediamediastream

Figuring out current torch state


Suppose I have a MediaStream captured through getUserMedia. If this is a rear facing camera on a smartphone, I can turn on/off the light like so:

const videoTrack = mediaStream.getVideoTracks()[0];
videoTrack.applyConstraints({
  advanced: [
    { torch: true }
  ]
});

I would like to toggle this state, so I need to figure out a way to get it. It does seem to be available via getSettings():

videoTrack.getSettings().torch; // false

However, it always seems to return false no matter what I set the current constraints to.

What is the correct method for getting the state of the torch, and ideally other advanced constraints of the video stream/camera?


Solution

  • Just anecdotally, support for torch seems limited to Chrome for Android on devices like the Google Pixel at the moment.

    About your code, the applyConstraints method is asynchronous. It takes time for the setting to apply, so you must await the promise it returns, before you can read the result of the modification. Try this using async/await:

    async function (mediaStream) {
      const videoTrack = mediaStream.getVideoTracks()[0];
    
      await videoTrack.applyConstraints({torch: true});
      console.log(videoTrack.getSettings().torch); // true
    };
    

    ...or using then to form a promise chain:

    function (mediaStream) {
      const videoTrack = mediaStream.getVideoTracks()[0];
    
      return videoTrack.applyConstraints({torch: true})
        .then(() => console.log(videoTrack.getSettings().torch)); // true
    };
    

    Thirdly, there's nothing advanced about advanced: [], an older more complicated syntax. Today's modern syntax is simpler.