Spaces:
Running on Zero
Running on Zero
File size: 4,994 Bytes
3e6f84d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 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 }
}
|