Spaces:
Running

File size: 5,565 Bytes
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83ef6d
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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<string>('disconnected');

    // Refs
    const socketRef = useRef<WebSocket | null>(null);
    const audioContextRef = useRef<AudioContext | null>(null);
    const processorRef = useRef<ScriptProcessorNode | null>(null); // Deprecated but works everywhere. Use AudioWorklet for prod.
    const inputRef = useRef<MediaStreamAudioSourceNode | null>(null);
    const audioQueueRef = useRef<Blob[]>([]);
    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
    };
};