Spaces:
Sleeping
Sleeping
| 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; | |
| } |