How do I auto set and choose a camera that has a torch feature built-in it in react js

  Kiến thức lập trình

I have a QR code scanner in my web app. I’m planning to add a flashlight feature to ease scanning QR for mobile users. As starters, for mobile users when they open the scanner, it will automatically choose device camera that is label back to open the environment camera. My problem is, in testing mobile, I am using Samsung s23 Ultra and it shows in console that it has two back cameras: one has a torch feature and the other doesn’t. How do I automatically choose the camera that has a torch feature when initializing the scanner?

  const initializeScanner = async () => {
      try {
        const cameras = await Html5Qrcode.getCameras();
        if (cameras && cameras.length > 0) {
          const cameraId = await getCameraId(cameras);
          startScanner(cameraId);
        } else {
          console.error('No cameras found.');
        }
      } catch (error) {
        console.error('Error getting cameras:', error);
        showToastMessage();
        handleCloseScanner();
      }
    };


const getCameraId = async (cameras) => {
    console.log("cameratest1", cameras)
    const isMobileDevice = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    if (isMobileDevice) {
      const environmentCamera = cameras.find(camera => camera.label.toLowerCase().includes('back'));
      for (const camera of environmentCamera) {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { deviceId: camera.deviceId }
        });
        const track = stream.getVideoTracks()[0];
        console.log("track", track)
        const capabilities = track.getCapabilities();
        console.log("cap", capabilities)
        if (capabilities.torch) {
          return camera.deviceId;
        }
      }
      return cameras[0].deviceId;
    } else {
      return cameras[0].id;
    }
  };

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT