Skip to content

Commit

Permalink
chore: improve cameras selection method
Browse files Browse the repository at this point in the history
  • Loading branch information
aineo committed Jul 2, 2024
1 parent 074e116 commit d492b23
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/lib/zxing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,32 @@ export class Scanner {
}

async getCameras() {
// Get only first two video devices. First - front camera, second (if available) - back camera
return (await navigator.mediaDevices.enumerateDevices())
.filter((device) => device.kind === 'videoinput')
.slice(0, 2)
const deviceCameras = (await navigator.mediaDevices.enumerateDevices()).filter(
(device) => device.kind === 'videoinput'
)

// Change only two video devices. First - front camera, second (is available) - back camera
const cameras: MediaDeviceInfo[] = []
if (deviceCameras.length > 0) {
cameras.push(deviceCameras[0])

if (deviceCameras.length > 1) {
let backCamera
if (navigator.userAgent.indexOf('iPhone'.toLowerCase())) {
// On iOS devices the device name can be localized
// But the second camera is back
backCamera = deviceCameras[1]
} else {
// Devices with other mobile os may have two front cameras
// So let's take first back camera
backCamera = deviceCameras.slice(1).find((device) => device.label.includes('back'))
}

if (backCamera) cameras.push(backCamera)
}
}

return cameras
}

stop(controls: IScannerControls) {
Expand Down

0 comments on commit d492b23

Please sign in to comment.