Created
September 26, 2023 19:30
-
-
Save theisof/79d634c307f54376d5dbd8aede7e4395 to your computer and use it in GitHub Desktop.
React hook for reading/requesting microphone permission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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