Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useCallback, useEffect, useRef, useState } from 'react'
- export const useRecordAudio = () => {
- const [audioChunks, setAudioChunks] = useState<BlobPart[]>([])
- const [audioUrl, setAudioUrl] = useState<string | null>(null)
- const [audioFile, setAudioFile] = useState<File | null>(null)
- const mediaRecorder = useRef<MediaRecorder | null>(null)
- const checkForPermissionsAndCreateStream = useCallback(async () => {
- if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
- try {
- if (mediaRecorder.current) {
- return
- }
- const stream = await navigator.mediaDevices.getUserMedia({
- audio: true,
- })
- mediaRecorder.current = new MediaRecorder(stream)
- } catch (err) {
- return null
- }
- }
- return null
- }, [mediaRecorder])
- const startRecording = useCallback(async () => {
- await checkForPermissionsAndCreateStream()
- if (mediaRecorder.current) {
- mediaRecorder.current.start()
- }
- }, [checkForPermissionsAndCreateStream])
- const stopRecording = useCallback(() => {
- if (mediaRecorder.current) {
- mediaRecorder.current.stop()
- }
- }, [])
- useEffect(() => {
- if (mediaRecorder.current) {
- mediaRecorder.current.ondataavailable = (event) => {
- setAudioChunks((prev) => [...prev, event.data])
- }
- mediaRecorder.current.onstop = () => {
- const audioBlob = new Blob(audioChunks, {
- type: 'audio/wav',
- })
- const audioUrlFromRecording = URL.createObjectURL(audioBlob)
- const audioFileFromRecording = new File(
- [audioBlob],
- `recording-${new Date().toLocaleDateString()}.wav`,
- )
- setAudioUrl(audioUrlFromRecording)
- setAudioFile(audioFileFromRecording)
- // Reset audio chunks
- setAudioChunks([])
- }
- }
- }, [audioChunks])
- return {
- audioChunks,
- audioUrl,
- audioFile,
- startRecording,
- stopRecording,
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement