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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
import { useState, useCallback, useRef, useEffect } from "react";
import { SPEAK_ENDPOINT } from "../lib/api";
export type SpeakStatus =
| "disconnected"
| "connecting"
| "connected"
| "loading_model"
| "speaking"
| "error";
export interface SpeakWebSocketState {
status: SpeakStatus;
error: string | null;
}
export function useSpeakWebSocket() {
const [state, setState] = useState<SpeakWebSocketState>({
status: "disconnected",
error: null,
});
const wsRef = useRef<WebSocket | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const audioQueueRef = useRef<Float32Array[]>([]);
const isPlayingRef = useRef(false);
const modelLoadingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const nextPlayTimeRef = useRef(0);
// Clean up on unmount
useEffect(() => {
return () => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (audioContextRef.current) {
audioContextRef.current.close();
audioContextRef.current = null;
}
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
};
}, []);
const getAudioContext = useCallback((): AudioContext => {
if (!audioContextRef.current || audioContextRef.current.state === "closed") {
audioContextRef.current = new AudioContext({ sampleRate: 24000 });
}
return audioContextRef.current;
}, []);
const playAudioQueue = useCallback(() => {
if (isPlayingRef.current) return;
isPlayingRef.current = true;
const ctx = getAudioContext();
function scheduleNext() {
const chunk = audioQueueRef.current.shift();
if (!chunk) {
isPlayingRef.current = false;
return;
}
const buffer = ctx.createBuffer(1, chunk.length, 24000);
buffer.copyToChannel(chunk, 0);
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
// Schedule playback at the right time to avoid gaps
const now = ctx.currentTime;
const startTime = Math.max(now, nextPlayTimeRef.current);
source.start(startTime);
nextPlayTimeRef.current = startTime + buffer.duration;
source.onended = () => {
if (audioQueueRef.current.length > 0) {
scheduleNext();
} else {
isPlayingRef.current = false;
}
};
}
scheduleNext();
}, [getAudioContext]);
const connect = useCallback((): Promise<boolean> => {
return new Promise((resolve) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
resolve(true);
return;
}
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
setState({ status: "connecting", error: null });
try {
const ws = new WebSocket(SPEAK_ENDPOINT);
ws.binaryType = "arraybuffer";
wsRef.current = ws;
ws.onopen = () => {
setState({ status: "connected", error: null });
resolve(true);
};
ws.onmessage = (event) => {
// Binary data = PCM audio chunk
if (event.data instanceof ArrayBuffer) {
// Clear model loading timer on first audio data
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
// Update status to speaking if not already
setState((s) => {
if (s.status === "loading_model" || s.status === "connected") {
return { ...s, status: "speaking" };
}
return s;
});
// Convert PCM16 LE to Float32
const pcm16 = new Int16Array(event.data);
const float32 = new Float32Array(pcm16.length);
for (let i = 0; i < pcm16.length; i++) {
float32[i] = pcm16[i] / 32768;
}
audioQueueRef.current.push(float32);
playAudioQueue();
return;
}
// Text data = JSON message
try {
const message = JSON.parse(event.data);
switch (message.type) {
case "audio_end":
// Clear model loading timer
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
// Wait for audio queue to drain, then go back to connected
// Use a short delay to let buffered audio finish
{
const checkDone = () => {
if (audioQueueRef.current.length === 0 && !isPlayingRef.current) {
setState((s) => {
if (s.status === "speaking" || s.status === "loading_model") {
return { ...s, status: "connected" };
}
return s;
});
} else {
setTimeout(checkDone, 100);
}
};
checkDone();
}
break;
case "error":
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
setState({
status: "error",
error: message.message || `Error: ${message.code}`,
});
break;
}
} catch {
console.error("Failed to parse speak WebSocket message:", event.data);
}
};
ws.onerror = () => {
setState({
status: "error",
error: "Failed to connect to speak server",
});
resolve(false);
};
ws.onclose = (event) => {
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
let errorMessage: string | null = null;
if (event.code === 1006) {
errorMessage = "Connection failed - server may be unavailable";
} else if (event.code !== 1000 && event.code !== 1001) {
errorMessage = `Connection closed unexpectedly (code: ${event.code})`;
}
setState((s) => ({
status: "disconnected",
error: errorMessage || s.error,
}));
wsRef.current = null;
};
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to create WebSocket connection";
setState({ status: "error", error: message });
resolve(false);
}
});
}, [playAudioQueue]);
const speak = useCallback(
async (text: string) => {
if (!text.trim()) return;
// Connect if not connected
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
const connected = await connect();
if (!connected) return;
}
// Reset audio state
audioQueueRef.current = [];
isPlayingRef.current = false;
nextPlayTimeRef.current = 0;
// Resume audio context if suspended (browser autoplay policy)
const ctx = getAudioContext();
if (ctx.state === "suspended") {
await ctx.resume();
}
// Start loading timer - if no audio arrives in 2 seconds, show loading state
modelLoadingTimerRef.current = setTimeout(() => {
setState((s) => {
if (s.status === "connected" || s.status === "connecting") {
return { ...s, status: "loading_model" };
}
return s;
});
modelLoadingTimerRef.current = null;
}, 2000);
// Send speak request
wsRef.current?.send(
JSON.stringify({ type: "speak", text })
);
setState((s) => ({ ...s, error: null }));
},
[connect, getAudioContext]
);
const cancel = useCallback(() => {
// Clear audio queue
audioQueueRef.current = [];
isPlayingRef.current = false;
nextPlayTimeRef.current = 0;
// Clear model loading timer
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
// Send cancel message
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "cancel" }));
}
setState((s) => ({
...s,
status: wsRef.current?.readyState === WebSocket.OPEN ? "connected" : "disconnected",
}));
}, []);
const disconnect = useCallback(() => {
// Clear audio queue
audioQueueRef.current = [];
isPlayingRef.current = false;
nextPlayTimeRef.current = 0;
if (modelLoadingTimerRef.current) {
clearTimeout(modelLoadingTimerRef.current);
modelLoadingTimerRef.current = null;
}
if (wsRef.current) {
// Send stop message before closing
if (wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "stop" }));
}
wsRef.current.close(1000, "User disconnected");
wsRef.current = null;
}
setState({ status: "disconnected", error: null });
}, []);
return {
...state,
isConnected:
state.status === "connected" ||
state.status === "speaking" ||
state.status === "loading_model",
isSpeaking: state.status === "speaking",
isModelLoading: state.status === "loading_model",
speak,
cancel,
connect,
disconnect,
};
}
|