Advertisement
metalni

recording audio

Oct 18th, 2023
1,188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useCallback, useEffect, useRef, useState } from 'react'
  2.  
  3. export const useRecordAudio = () => {
  4.   const [audioChunks, setAudioChunks] = useState<BlobPart[]>([])
  5.   const [audioUrl, setAudioUrl] = useState<string | null>(null)
  6.   const [audioFile, setAudioFile] = useState<File | null>(null)
  7.   const mediaRecorder = useRef<MediaRecorder | null>(null)
  8.  
  9.   const checkForPermissionsAndCreateStream = useCallback(async () => {
  10.     if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  11.       try {
  12.         if (mediaRecorder.current) {
  13.           return
  14.         }
  15.  
  16.         const stream = await navigator.mediaDevices.getUserMedia({
  17.           audio: true,
  18.         })
  19.  
  20.         mediaRecorder.current = new MediaRecorder(stream)
  21.       } catch (err) {
  22.         return null
  23.       }
  24.     }
  25.  
  26.     return null
  27.   }, [mediaRecorder])
  28.  
  29.   const startRecording = useCallback(async () => {
  30.     await checkForPermissionsAndCreateStream()
  31.     if (mediaRecorder.current) {
  32.       mediaRecorder.current.start()
  33.     }
  34.   }, [checkForPermissionsAndCreateStream])
  35.  
  36.   const stopRecording = useCallback(() => {
  37.     if (mediaRecorder.current) {
  38.       mediaRecorder.current.stop()
  39.     }
  40.   }, [])
  41.  
  42.   useEffect(() => {
  43.     if (mediaRecorder.current) {
  44.       mediaRecorder.current.ondataavailable = (event) => {
  45.         setAudioChunks((prev) => [...prev, event.data])
  46.       }
  47.  
  48.       mediaRecorder.current.onstop = () => {
  49.         const audioBlob = new Blob(audioChunks, {
  50.           type: 'audio/wav',
  51.         })
  52.  
  53.         const audioUrlFromRecording = URL.createObjectURL(audioBlob)
  54.         const audioFileFromRecording = new File(
  55.           [audioBlob],
  56.           `recording-${new Date().toLocaleDateString()}.wav`,
  57.         )
  58.         setAudioUrl(audioUrlFromRecording)
  59.         setAudioFile(audioFileFromRecording)
  60.  
  61.         // Reset audio chunks
  62.         setAudioChunks([])
  63.       }
  64.     }
  65.   }, [audioChunks])
  66.  
  67.   return {
  68.     audioChunks,
  69.     audioUrl,
  70.     audioFile,
  71.     startRecording,
  72.     stopRecording,
  73.   }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement