import { useRef, useState, useEffect } from 'react'; // Configuration const SAMPLE_RATE = 24000; // Match OpenAI/Standard const CHUNK_SIZE = 4096; export const useAudioStream = (token: string, backendUrl: string = 'ws://localhost:8000') => { const [isConnected, setIsConnected] = useState(false); const [isRecording, setIsRecording] = useState(false); const [isSpeaking, setIsSpeaking] = useState(false); // AI is speaking const [status, setStatus] = useState('disconnected'); // Refs const socketRef = useRef(null); const audioContextRef = useRef(null); const processorRef = useRef(null); // Deprecated but works everywhere. Use AudioWorklet for prod. const inputRef = useRef(null); const audioQueueRef = useRef([]); const isPlayingRef = useRef(false); const nextPlayTimeRef = useRef(0); // Initial Connection const connect = () => { if (!token) return; const wsUrl = `${backendUrl}/ws/voice/stream?token=${token}`; const ws = new WebSocket(wsUrl); ws.onopen = () => { setIsConnected(true); setStatus('connected'); }; ws.onclose = () => { setIsConnected(false); setStatus('disconnected'); }; ws.onmessage = async (event) => { const data = event.data; if (data instanceof Blob) { // Received Audio console.log("🔊 Received audio chunk:", data.size); playAudioChunk(data); } else { // Assume JSON Control Message try { const msg = JSON.parse(data); if (msg.status) { setStatus(msg.status); if (msg.status === 'speaking') setIsSpeaking(true); if (msg.status === 'listening') setIsSpeaking(false); } } catch (e) { console.error("WS Parse error", e); } } }; socketRef.current = ws; }; const startRecording = async () => { if (!socketRef.current || socketRef.current.readyState !== WebSocket.OPEN) return; try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const ctx = new (window.AudioContext || (window as any).webkitAudioContext)({ sampleRate: SAMPLE_RATE }); audioContextRef.current = ctx; const source = ctx.createMediaStreamSource(stream); inputRef.current = source; // Create Processor // BufferSize: 4096 is good balance ~170ms latency const processor = ctx.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (e) => { if (!isRecording) return; const inputData = e.inputBuffer.getChannelData(0); // Convert Float32 to Int16 for simple transport (or send Float32 and decode on server) // For MVP: Send raw bytes or convert. // Let's Convert to Int16 PCM to save bandwidth and match standard containers const pcmData = floatTo16BitPCM(inputData); if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) { socketRef.current.send(pcmData); } }; source.connect(processor); processor.connect(ctx.destination); // Need connection to destination for Chrome to fire processorRef.current = processor; setIsRecording(true); setStatus('listening'); } catch (e) { console.error("Mic Error:", e); } }; const stopRecording = () => { if (processorRef.current) { processorRef.current.disconnect(); processorRef.current = null; } if (inputRef.current) { inputRef.current.disconnect(); inputRef.current = null; } if (audioContextRef.current) { audioContextRef.current.close(); audioContextRef.current = null; } setIsRecording(false); // Send commit signal if (socketRef.current) { socketRef.current.send(JSON.stringify({ type: "commit" })); } }; const playAudioChunk = async (blob: Blob) => { // Use a shared AudioContext for playback const ctx = new (window.AudioContext || (window as any).webkitAudioContext)(); const arrayBuffer = await blob.arrayBuffer(); const audioBuffer = await ctx.decodeAudioData(arrayBuffer); const source = ctx.createBufferSource(); source.buffer = audioBuffer; source.connect(ctx.destination); source.start(0); }; // Helper: Float32 to Int16 const floatTo16BitPCM = (output: Float32Array) => { let offset = 0; const buffer = new ArrayBuffer(output.length * 2); const view = new DataView(buffer); for (let i = 0; i < output.length; i++, offset += 2) { let s = Math.max(-1, Math.min(1, output[i])); view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } return buffer; }; return { isConnected, isRecording, isSpeaking, status, connect, startRecording, stopRecording }; };