Advertisement
nopasteonlybin

useAudio.tsx

Dec 8th, 2023 (edited)
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export const useAudioRecorder = (onRecordingFinish: (e: BlobEvent) => void) => {
  2.     const [audioRecorder, setAudioRecorder] = useState<MediaRecorder>()
  3.  
  4.     const [recordingState, setRecordingState] = useState<RecordingState>('inactive')
  5.  
  6.     const [isMicReady, setIsMicReady] = useState<Boolean>(false)
  7.  
  8.     const [micPermission, setMicPermission] = useState<PermissionState>('prompt')
  9.  
  10.     const handleOnStart = (ev: Event) => {
  11.         setRecordingState('recording')
  12.     }
  13.  
  14.     const handleOnStop = (ev: Event) => {
  15.         setRecordingState('inactive')
  16.     }
  17.  
  18.     const handleAudioDataAvailable = (ev: BlobEvent) => {
  19.         onRecordingFinish(ev)
  20.     }
  21.  
  22.     const getMicPermission = async () => {
  23.         try {
  24.             if (window.MediaRecorder === undefined) throw Error('Audio recording facility not available on this device')
  25.  
  26.             const mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false })
  27.  
  28.             setMicPermission('granted')
  29.  
  30.             const audioRecorder = new MediaRecorder(mediaStream)
  31.  
  32.             audioRecorder.onstart = handleOnStart
  33.  
  34.             audioRecorder.onstop = handleOnStop
  35.  
  36.             audioRecorder.onerror = () => {
  37.                 console.log('error while recording audio')
  38.             }
  39.  
  40.             audioRecorder.ondataavailable = handleAudioDataAvailable
  41.  
  42.             setAudioRecorder(audioRecorder)
  43.  
  44.             setIsMicReady(true)
  45.         } catch (err) {
  46.             setMicPermission('denied')
  47.             setIsMicReady(false)
  48.         }
  49.     }
  50.  
  51.     useEffect(() => {
  52.         getMicPermission()
  53.     }, [])
  54.  
  55.     const startRecording = () => audioRecorder?.start()
  56.  
  57.     const stopRecording = () => audioRecorder?.stop()
  58.  
  59.     const pauseRecording = () => audioRecorder?.pause()
  60.  
  61.     const resumeRecording = () => audioRecorder?.resume()
  62.  
  63.     const getRecordingState = () => audioRecorder?.state
  64.  
  65.     const toggleAudioRecorderStartStop = () => {
  66.         if (!audioRecorder) throw Error('Audio device is undefined', audioRecorder)
  67.  
  68.         if (audioRecorder.state === 'inactive') startRecording()
  69.         else if (audioRecorder.state === 'recording') stopRecording()
  70.     }
  71.  
  72.     return {
  73.         toggleAudioRecorderStartStop,
  74.         recordingState,
  75.         isMicReady,
  76.         micPermission,
  77.     }
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement