【问题标题】:NodeJS - Turn On and Off Tourch/Flashlight in mobile Android/IPhoneNodeJS - 在移动 Android/iPhone 中打开和关闭 Tourch/手电筒
【发布时间】:2020-08-31 23:31:51
【问题描述】:

我有一个 nodeJS 项目,我在 System 和 Mobile 上都使用它。

我需要执行以下步骤 - 1.增加一个按钮来打开/关闭手电筒。 2. 仅当该功能支持时才应显示该按钮 手机和浏览器 3.灯应该默认关闭

当我使用下面提到的代码时,它会从我的系统启用我的网络摄像头闪光灯,但它无法在我的手机上运行。

闪光灯开/关

//Test browser support
const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;

if (SUPPORTS_MEDIA_DEVICES) {
  //Get the environment camera (usually the second one)
  navigator.mediaDevices.enumerateDevices().then(devices => {

    const cameras = devices.filter((device) => device.kind === 'videoinput');

    if (cameras.length === 0) {
      throw 'No camera found on this device.';
    }
    const camera = cameras[cameras.length - 1];

    // Create stream and get video track
    navigator.mediaDevices.getUserMedia({
      video: true
    }).then(stream => {
      const track = stream.getVideoTracks()[0];
      track.applyConstraints({
        advanced: [{torch: false}]
      });
      //Create image capture object and get camera capabilities
      const imageCapture = new ImageCapture(track)
      const photoCapabilities = imageCapture.getPhotoCapabilities().then(() => {

        //todo: check if camera has a torch

        //let there be light!
        const btn = document.querySelector('.switch');
        btn.addEventListener('click', function(){
            isTorchOn = !isTorchOn;
          track.applyConstraints({
            advanced: [{torch: isTorchOn}]
          });
        });
      });
    });
  });
  //The light will be on as long the track exists
}

谁能提出解决方案?

【问题讨论】:

  • 如果您的代码需要在每个移动设备上运行,我认为这是无法实现的。据我所知,只有在 Chrome 上才能通过浏览器访问相机控件。
  • 是的,Chrome 可以为我工作。我正在通过手机中的 chrome 访问它。

标签: node.js nodejs-stream mediastream


【解决方案1】:

对于网络 RTC, 将其用于设备上的 Torch 支持检查

var imageCapture = new ImageCapture(videoTrack);

var photoCapability = imageCapture.getPhotoCapabilities();

在浏览器上使用它来检查 Torch 支持

var mediaCapabilities = navigator.mediaDevices.getSupportedConstraints ()
 
 if (mediaCapabilities.torch && photoCapability.fillLightMode.length > 0){
          document.getElementById('torchButton').classList.remove("hidden");
          document.getElementById('torchButton').classList.add("block");
          console.log("Torch is enabled");
      }

然后基于函数调用

function startTorch(){
    var torchCheckBox = document.getElementById("torchButton");
    if(torchCheckBox.checked == true){
    videoTrack.applyConstraints({
        advanced: [{torch: true}]
      }).then(function() {
        //Do Success code here
      }).catch(handleError);
    }
    else{
        videoTrack.applyConstraints({
            advanced: [{torch: false}]
          }).then(function() {
            //success code here  
          }).catch(handleError);
    }
}

希望这会有所帮助!

【讨论】:

  • Iphone Safari 浏览器不支持闪光灯功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2019-09-18
  • 2015-01-28
  • 1970-01-01
相关资源
最近更新 更多