File size: 1,727 Bytes
3aea50a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import { useState, useCallback } from 'react'
export function useCameraDevices() {
const [devices, setDevices] = useState<MediaDeviceInfo[]>([])
const [activeDeviceId, setActiveDeviceId] = useState<string | null>(null)
const enumerateCameras = useCallback(async () => {
try {
const allDevices = await navigator.mediaDevices.enumerateDevices()
const videoInputs = allDevices.filter((d) => d.kind === 'videoinput')
setDevices(videoInputs)
return videoInputs
} catch {
return []
}
}, [])
const switchCamera = useCallback(
async (deviceId: string): Promise<MediaStream | null> => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
deviceId: { exact: deviceId },
width: { ideal: 640 },
height: { ideal: 480 },
},
audio: false,
})
setActiveDeviceId(deviceId)
return stream
} catch (err) {
console.error('Failed to switch camera:', err)
return null
}
},
[],
)
const getStreamForFacingMode = useCallback(
async (facingMode: 'user' | 'environment'): Promise<MediaStream | null> => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode,
width: { ideal: 640 },
height: { ideal: 480 },
},
audio: false,
})
return stream
} catch (err) {
console.error('Failed to get camera with facing mode:', err)
return null
}
},
[],
)
return {
devices,
activeDeviceId,
enumerateCameras,
switchCamera,
getStreamForFacingMode,
}
}
|