File size: 1,012 Bytes
364ff8c
 
 
 
 
 
 
 
 
 
 
d0bd0a6
 
 
 
 
364ff8c
d0bd0a6
 
 
 
 
364ff8c
d0bd0a6
 
 
 
 
 
 
 
 
 
 
 
 
 
3a0b0b9
364ff8c
 
 
d0bd0a6
 
 
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
const getWsUrl = () => {
  // In production (HuggingFace), use the same host
  if (window.location.hostname !== "localhost") {
    const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
    return `${protocol}//${window.location.host}/ws`;
  }
  // Local development
  return "ws://localhost:8000/ws";
};

const WS_URL = getWsUrl();

export function createSocket(onResult, onError) {
  const ws = new WebSocket(WS_URL);

  ws.onopen = () => {
    console.log("WebSocket connected to", WS_URL);
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      onResult(data);
    } catch (e) {
      console.error("Failed to parse server response", e);
    }
  };

  ws.onerror = (err) => {
    console.error("WebSocket error", err);
    if (onError) onError(err);
  };

  ws.onclose = () => {
    console.log("WebSocket disconnected");
  };

  ws.sendAudio = (buffer) => {
    if (ws.readyState !== WebSocket.OPEN) return;
    ws.send(buffer);
  };

  return ws;
}