How to Select the Primary Camera When Using react-qr-reader with facingMode set to environment?

32 Views Asked by At

I'm currently working with the react-qr-reader library (version 3.0.0-beta-1) in a project aimed at scanning QR codes. I've set the facingMode to environment to utilize the rear camera on mobile devices, which works as intended. However, I've encountered an issue where, on devices with multiple rear cameras, the library defaults to using the wide-angle camera. This has been problematic for QR code recognition.

I'm looking for a way to explicitly specify or prioritize the primary camera over the wide-angle or other specialized cameras when facingMode is set to environment. Does anyone know how to achieve this within the react-qr-reader settings, or through any workarounds?

Any suggestions or guidance would be greatly appreciated. Thank you in advance for your help!

To address this, I attempted a workaround using the navigator.mediaDevices.enumerateDevices() API to filter and select the primary camera manually. Here’s the approach I took:

useEffect(() => {
    navigator.mediaDevices
        .enumerateDevices()
        .then((devices) => {
            console.log(devices);
            const videoDevices = devices.filter(
                (device) => device.kind === 'videoinput'
            );
            console.log(videoDevices);
            const unwantedKeywords = ['telephoto', 'wide', 'ultra wide'];
            const backCamera = videoDevices.find(
                (device) =>
                    !unwantedKeywords.some((keyword) =>
                        device.label.toLowerCase().includes(keyword)
                    ) &&
                    !device.label.toLowerCase().includes('front') && // Exclude front cameras
                    !device.label.toLowerCase().includes('전면') // Exclude front cameras in other languages
            );
            const newConstraints = {
                video: backCamera
                    ? { deviceId: { exact: backCamera.deviceId } }
                    : { facingMode: 'environment' },
            };
            setConstraints(newConstraints);
        })
        .catch((error) => {
            console.error('Error accessing media devices.', error);
        });
}, []);

But it didn't well. Also, it was hard to check console in mobile. I don't know if this code works well (it didn't work when I did it), and I don't know if it's right to guess and write down all the labels in this way. Is there any way?

0

There are 0 best solutions below