Skip to content

Instantly share code, notes, and snippets.

@theisof
Created September 26, 2023 19:30
Show Gist options
  • Save theisof/79d634c307f54376d5dbd8aede7e4395 to your computer and use it in GitHub Desktop.
Save theisof/79d634c307f54376d5dbd8aede7e4395 to your computer and use it in GitHub Desktop.
React hook for reading/requesting microphone permission
import { useEffect, useState } from "react";
export type UsePermissionState = "granted" | "denied" | "prompt" | "loading";
export function useMicrophonePermission() {
const [permissionState, setPermissionState] =
useState<UsePermissionState>("loading");
useEffect(() => {
(window.navigator.permissions as any)
.query({ name: "microphone" })
.then(function (result: PermissionStatus) {
setPermissionState(result.state);
});
}, []);
const requestMicrophone = () => {
window.navigator.mediaDevices
.getUserMedia({ audio: true })
.then(() => {
setPermissionState("granted");
})
.catch(function (err) {
console.error("Microphone access error:", err);
setPermissionState("denied");
});
};
return {
permissionState,
requestMicrophone,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment