弄清楚当前的手电筒状态

Figuring out current torch state

假设我有一个通过 getUserMedia 捕获的 MediaStream。如果这是智能手机上的后置摄像头,我可以 on/off 像这样转动灯:

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

我想切换这个状态,所以我需要想办法得到它。它似乎可以通过 getSettings():

获得
videoTrack.getSettings().torch; // false

但是,无论我将当前约束设置为什么,它似乎总是 return false

获取 torch 状态的正确方法是什么,最好是获取视频的其他高级约束 stream/camera?

有趣的是,目前 Google Pixel 等设备上 Android 对 torch 的支持似乎仅限于 Chrome。

关于您的代码,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 使用 async/await:

async function (mediaStream) {
  const videoTrack = mediaStream.getVideoTracks()[0];

  await videoTrack.applyConstraints({torch: true});
  console.log(videoTrack.getSettings().torch); // true
};

...或使用 then 形成承诺链:

function (mediaStream) {
  const videoTrack = mediaStream.getVideoTracks()[0];

  return videoTrack.applyConstraints({torch: true})
    .then(() => console.log(videoTrack.getSettings().torch)); // true
};

第三,advanced: [] 没有任何先进之处,这是一种较旧的更复杂的语法。今天的modern syntax比较简单