useDevices
The useDevices hook provides functionality to interact with the different media devices available to you, like your camera, microphone, and speaker.
Name | Description | Return Type | Params |
---|---|---|---|
devices | The available media devices. | MediaDeviceInfo[] | |
preferredDeviceId | The preferred media device's ID. | string | null | |
preferredDevice | The preferred media device. | MediaDeviceInfo | null | |
fetchStream | Fetch media stream from the selected media device. | Promise<FetchStreamResponse> | { mediaDeviceKind: "mic" | "cam"; } |
getPermission | Get permission to access the selected media device. | Promise<{permission: "granted" | "denied"; error?: StreamPermissionsError | undefined;}> | |
setPreferredDevice | Set the preferred media device. | void | string |
Example Usage
const {
devices,
preferredDeviceId,
preferredDevice,
fetchStream,
getPermission,
setPreferredDevice,
} = useDevices({
type: "cam",
onPermissionGranted() {},
onPermissionDenied() {},
onDeviceChanged(deviceId: string) {},
});
// Change preferred device
const changePreferredDevice = (deviceId: string) => {
setPreferredDevice(deviceId);
};
// Fetch media stream from preferred device
const fetchMediaStream = async () => {
const { stream, error } = await fetchStream({
mediaDeviceKind: "cam",
});
if (error) {
return;
}
return stream;
};
Props
The useDevices hook accepts an object with the following fields as props.
type
Required
Description | Type |
---|---|
The device type. | "mic" | "cam" | "speaker" |
Example Usage
// Get all media devices of type "cam"
const { devices } = useDevices({ type: "cam" });
// Get all media devices of type "mic"
const { devices } = useDevices({ type: "mic" });
// Get all media devices of type "speaker"
const { devices } = useDevices({ type: "speaker" });
onPermissionGranted
Optional
Description | Return Type |
---|---|
This function will be called when the permission for accessing the device is granted. | void |
Example Usage
useDevices({ type: "cam", onPermissionGranted: () => {
console.log("Permission for accessing the device was granted!");
// your code here
}});
onPermissionDenied
Optional
Description | Return Type |
---|---|
This function will be called when the permission for accessing the device is denied. | void |
Example Usage
useDevices({ type: "cam", onPermissionDenied: () => {
console.log("Permission for accessing the device was denied!");
// your code here
}});
onDeviceChanged
Optional
Description | Return Type |
---|---|
This function will be called when the preferred device is changed. | void |
Parameter Name | Type | Description | Required |
---|---|---|---|
deviceId | string | Device ID of changed preferred device. | Yes |
Example Usage
useDevices({ type: "cam", onDeviceChanged: (deviceId: string) => {
console.log("Changed preferred device to: ", deviceId);
// your code here
}});