From 47a0f113a72bf626ee537b947f3e6d45a233d774 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Mon, 29 Dec 2025 11:32:17 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=8A=20refactor:=20Audio=20Chunk=20Hand?= =?UTF-8?q?ling=20for=20STT=20(#11140)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replaced local state for audio chunks with a ref to improve performance and memory management. - Updated event listeners to utilize the new audioChunksRef for data handling. - Cleaned up the cleanup function to remove unnecessary event listener removals. - Enhanced the handleStop function to reset audio chunks using the ref, ensuring better state management. --- .../src/hooks/Input/useSpeechToTextExternal.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/client/src/hooks/Input/useSpeechToTextExternal.ts b/client/src/hooks/Input/useSpeechToTextExternal.ts index 0376279ce5..bbe2d188a2 100644 --- a/client/src/hooks/Input/useSpeechToTextExternal.ts +++ b/client/src/hooks/Input/useSpeechToTextExternal.ts @@ -17,9 +17,9 @@ const useSpeechToTextExternal = ( const audioContextRef = useRef(null); const mediaRecorderRef = useRef(null); + const audioChunksRef = useRef([]); const [permission, setPermission] = useState(false); const [isListening, setIsListening] = useState(false); - const [audioChunks, setAudioChunks] = useState([]); const [isRequestBeingMade, setIsRequestBeingMade] = useState(false); const [audioMimeType, setAudioMimeType] = useState(() => getBestSupportedMimeType()); @@ -92,10 +92,6 @@ const useSpeechToTextExternal = ( const cleanup = () => { if (mediaRecorderRef.current) { - mediaRecorderRef.current.removeEventListener('dataavailable', (event: BlobEvent) => { - audioChunks.push(event.data); - }); - mediaRecorderRef.current.removeEventListener('stop', handleStop); mediaRecorderRef.current = null; } }; @@ -114,11 +110,11 @@ const useSpeechToTextExternal = ( }; const handleStop = () => { - if (audioChunks.length > 0) { - const audioBlob = new Blob(audioChunks, { type: audioMimeType }); + if (audioChunksRef.current.length > 0) { + const audioBlob = new Blob(audioChunksRef.current, { type: audioMimeType }); const fileExtension = getFileExtension(audioMimeType); - setAudioChunks([]); + audioChunksRef.current = []; const formData = new FormData(); formData.append('audio', audioBlob, `audio.${fileExtension}`); @@ -178,7 +174,7 @@ const useSpeechToTextExternal = ( if (audioStream.current) { try { - setAudioChunks([]); + audioChunksRef.current = []; const bestMimeType = getBestSupportedMimeType(); setAudioMimeType(bestMimeType); @@ -186,7 +182,7 @@ const useSpeechToTextExternal = ( mimeType: audioMimeType, }); mediaRecorderRef.current.addEventListener('dataavailable', (event: BlobEvent) => { - audioChunks.push(event.data); + audioChunksRef.current.push(event.data); }); mediaRecorderRef.current.addEventListener('stop', handleStop); mediaRecorderRef.current.start(100);