137 lines
4.8 KiB
TypeScript
137 lines
4.8 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
|
|
import {
|
|
getSpeechRecognition as getBrowserSpeechRecognition,
|
|
isIosStandalone,
|
|
type SpeechRecognitionConstructor,
|
|
} from '@/lib/speech-recognition'
|
|
|
|
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
|
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
|
|
|
|
const ERROR_MESSAGES: Record<string, string> = {
|
|
'not-allowed': 'Permite el acceso al micrófono para dictar.',
|
|
'service-not-allowed': 'El dictado no está disponible en este navegador.',
|
|
'audio-capture': 'No encontramos un micrófono.',
|
|
network: 'Sin conexión para reconocer la voz.',
|
|
}
|
|
|
|
/**
|
|
* The browser's speech recognition, or `null` when there is none. An iOS home-screen
|
|
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
|
* unsupported (the keyboard's own dictation still works).
|
|
*/
|
|
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
|
if (typeof window === 'undefined' || isIosStandalone()) return null
|
|
|
|
return getBrowserSpeechRecognition()
|
|
}
|
|
|
|
type UseDictationOptions = {
|
|
/** Called once with the whole transcript when the user stops talking. */
|
|
onTranscript: (transcript: string) => void
|
|
}
|
|
|
|
/**
|
|
* Quiet time after the last words heard that ends the dictation. Safari on iOS keeps
|
|
* listening long after the user stops talking even with `continuous = false`, so the
|
|
* phrase is delivered once nothing new has been heard for this long.
|
|
*/
|
|
export const DICTATION_SILENCE_MS = 3000
|
|
|
|
/** A recognition in progress: `finish` delivers what was heard, `cancel` drops it. */
|
|
type DictationSession = { finish: () => void; cancel: () => void }
|
|
|
|
/**
|
|
* Dictation with the Web Speech API in Argentine Spanish: one phrase per `start()`
|
|
* (`continuous = false`), with the partial transcript in `interim` while the user
|
|
* talks. The phrase is delivered when the browser ends the recognition, when the user
|
|
* stops it, or after `DICTATION_SILENCE_MS` without new words, whichever comes first.
|
|
* `no-speech` and `aborted` are ignored; any other error is in `error`.
|
|
*/
|
|
export function useDictation({ onTranscript }: UseDictationOptions) {
|
|
const [supported] = useState(() => getSpeechRecognition() !== null)
|
|
const [listening, setListening] = useState(false)
|
|
const [interim, setInterim] = useState('')
|
|
const [error, setError] = useState<string | null>(null)
|
|
const sessionRef = useRef<DictationSession | null>(null)
|
|
const onTranscriptRef = useRef(onTranscript)
|
|
|
|
useEffect(() => {
|
|
onTranscriptRef.current = onTranscript
|
|
})
|
|
|
|
// Leaving the page stops listening, without delivering a transcript.
|
|
useEffect(() => () => sessionRef.current?.cancel(), [])
|
|
|
|
const start = useCallback(() => {
|
|
const SpeechRecognition = getSpeechRecognition()
|
|
if (!SpeechRecognition || sessionRef.current) return
|
|
|
|
const recognition = new SpeechRecognition()
|
|
recognition.lang = 'es-AR'
|
|
recognition.interimResults = true
|
|
recognition.continuous = false
|
|
recognition.maxAlternatives = 1
|
|
|
|
let transcript = ''
|
|
let failed = false
|
|
let done = false
|
|
let silenceTimer: ReturnType<typeof setTimeout> | undefined
|
|
|
|
// Runs once, whatever ends the dictation first; aborting afterwards only fires an
|
|
// ignored `aborted` error and an `onend` that finds the session already done.
|
|
const end = (deliver: boolean) => {
|
|
if (done) return
|
|
done = true
|
|
clearTimeout(silenceTimer)
|
|
sessionRef.current = null
|
|
setListening(false)
|
|
setInterim('')
|
|
recognition.abort()
|
|
if (deliver && transcript && !failed) onTranscriptRef.current(transcript)
|
|
}
|
|
|
|
recognition.onresult = (event) => {
|
|
// The results hold the whole phrase so far: final parts plus the guess in progress.
|
|
transcript = Array.from(event.results, (result) => result[0].transcript)
|
|
.join('')
|
|
.trim()
|
|
setInterim(transcript)
|
|
|
|
clearTimeout(silenceTimer)
|
|
silenceTimer = setTimeout(() => end(true), DICTATION_SILENCE_MS)
|
|
}
|
|
|
|
recognition.onerror = (event) => {
|
|
if (IGNORED_ERRORS.has(event.error)) return
|
|
failed = true
|
|
setError(ERROR_MESSAGES[event.error] ?? 'No pudimos reconocer la voz.')
|
|
}
|
|
|
|
// Some browsers (iOS Safari) end without marking the last result as final, so
|
|
// whatever was heard by then is the transcript.
|
|
recognition.onend = () => end(true)
|
|
|
|
setError(null)
|
|
setInterim('')
|
|
|
|
try {
|
|
recognition.start()
|
|
} catch {
|
|
setError('No pudimos empezar a escuchar.')
|
|
return
|
|
}
|
|
|
|
sessionRef.current = { finish: () => end(true), cancel: () => end(false) }
|
|
setListening(true)
|
|
}, [])
|
|
|
|
/** Stops listening right away; what was heard so far is still delivered. */
|
|
const stop = useCallback(() => sessionRef.current?.finish(), [])
|
|
|
|
const clearError = useCallback(() => setError(null), [])
|
|
|
|
return { supported, listening, interim, error, start, stop, clearError }
|
|
}
|