import { useEffect, useRef, useState } from 'react' export const MAX_SECONDS = 120 export const MAX_BYTES = 12 * 1024 * 1024 export function useRecorder() { const [blob, setBlob] = useState(null) const [url, setUrl] = useState('') const [recording, setRecording] = useState(false) const [pending, setPending] = useState(false) const [seconds, setSeconds] = useState(0) const [error, setError] = useState('') const [notice, setNotice] = useState('') const recorder = useRef(null) const stream = useRef(null) const timer = useRef(null) const alive = useRef(true) const requesting = useRef(false) const generation = useRef(0) useEffect(() => { alive.current = true return () => { alive.current = false generation.current += 1 clearInterval(timer.current) if (recorder.current?.state === 'recording') recorder.current.stop() stream.current?.getTracks().forEach(track => track.stop()) } }, []) useEffect(() => { if (!blob) { setUrl(''); return } const nextUrl = URL.createObjectURL(blob) setUrl(nextUrl) return () => URL.revokeObjectURL(nextUrl) }, [blob]) function stop() { if (recorder.current?.state === 'recording') recorder.current.stop() stream.current?.getTracks().forEach(track => track.stop()) clearInterval(timer.current) } async function start() { if (requesting.current || recorder.current?.state === 'recording') return setError('') setNotice('') if (!navigator.mediaDevices?.getUserMedia || !window.MediaRecorder) { setError('This browser cannot record here. Open localhost in a recent Edge or Chrome, upload audio, or continue without recording.') return } requesting.current = true setPending(true) const currentGeneration = generation.current try { const input = await navigator.mediaDevices.getUserMedia({ audio: true }) if (!alive.current || currentGeneration !== generation.current) { input.getTracks().forEach(track => track.stop()) return } stream.current = input const mimeType = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4'].find(type => MediaRecorder.isTypeSupported(type)) const instance = new MediaRecorder(input, mimeType ? { mimeType } : undefined) recorder.current = instance const chunks = [] let bytes = 0 let tooLarge = false instance.ondataavailable = event => { bytes += event.data.size if (bytes > MAX_BYTES) { tooLarge = true stop() } else if (event.data.size) chunks.push(event.data) } instance.onerror = () => { if (alive.current) setError('Recording was interrupted. Replay any captured audio, or record again.') stop() } instance.onstop = () => { clearInterval(timer.current) input.getTracks().forEach(track => track.stop()) if (!alive.current) return setRecording(false) if (tooLarge) { setError('Recording exceeded 12 MB. Try a shorter recording.'); return } const result = new Blob(chunks, { type: instance.mimeType || 'audio/webm' }) if (result.size) setBlob(result) else setError('No audio was captured. Please try again.') } instance.start(250) setBlob(null) setSeconds(0) setRecording(true) const started = Date.now() timer.current = setInterval(() => { const elapsed = Math.floor((Date.now() - started) / 1000) if (alive.current) setSeconds(Math.min(elapsed, MAX_SECONDS)) // Leave one second for the final encoded packet and timer scheduling. if (elapsed >= MAX_SECONDS - 1) { if (alive.current) setNotice('Stopped just before the two-minute limit. You can replay and transcribe this recording.') stop() } }, 250) } catch (failure) { stream.current?.getTracks().forEach(track => track.stop()) if (alive.current) { const messages = { NotAllowedError: 'Microphone permission was denied. Allow it in your browser, upload audio, or continue without recording.', NotFoundError: 'No microphone was found. Connect one or upload an audio file.', NotReadableError: 'The microphone is unavailable. Close other apps using it and try again.', } setError(messages[failure.name] || 'Could not start recording. Try again or continue without recording.') } } finally { requesting.current = false if (alive.current) setPending(false) } } function chooseFile(file) { if (!file) return setError('') setNotice('') if (file.size > MAX_BYTES) { setError('Choose an audio file smaller than 12 MB.'); return } if (!file.size) { setError('That file is empty. Choose another recording.'); return } setBlob(file) setSeconds(0) } return { blob, url, recording, pending, seconds, error, notice, start, stop, chooseFile } }