useDevices

useDevices

The useDevices hook provides functionality to interact with the different media devices available to you, like your camera, microphone, and speaker.

NameDescriptionReturn TypeParams
devicesThe available media devices.MediaDeviceInfo[]
preferredDeviceIdThe preferred media device's ID.string | null
preferredDeviceThe preferred media device.MediaDeviceInfo | null
fetchStreamFetch media stream from the selected media device.Promise<FetchStreamResponse>{ mediaDeviceKind: "mic" | "cam"; }
getPermissionGet permission to access the selected media device.Promise<{permission: "granted" | "denied"; error?: StreamPermissionsError | undefined;}>
setPreferredDeviceSet the preferred media device.voidstring

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
DescriptionType
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
DescriptionReturn 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
DescriptionReturn 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
DescriptionReturn Type
This function will be called when the preferred device is changed.void
Parameter NameTypeDescriptionRequired
deviceIdstringDevice ID of changed preferred device.Yes

Example Usage

useDevices({
  type: "cam",
  onDeviceChanged: (deviceId: string) => {
    console.log("Changed preferred device to: ", deviceId);
    // your code here
  },
});
Audio/Video Infrastructure designed for developers to empower them to ship simple yet powerful Audio/Video Apps.
support
company
Copyright © 2024 Graphene 01, Inc. All Rights Reserved.