Spaces:
Paused
Paused
Download index.html from Simzy/world-room: direct link, hf CLI and curl.
- Browser
- Download file 24.7 kB
-
https://huggingface.co/spaces/Simzy/world-room/resolve/main/index.html
- Command line
-
hf download hf://spaces/Simzy/world-room/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Simzy/world-room/resolve/main/index.html
24.7 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>World Room — Talk to your worldbuilder</title> | |
| <style> | |
| /* ========================================================================== | |
| DEVELOPER NOTES | |
| ========================================================================== | |
| World Room — creative realtime audio app using the OpenAI Realtime API + WebRTC | |
| LATENCY | |
| WebRTC offers ~300 ms end-to-end. The data channel ("oai-events") | |
| carries transcript + lifecycle events alongside the audio stream. | |
| SESSION LIFECYCLE | |
| The ephemeral key (ek_...) returned by /api/session expires — check | |
| `expires_at`. Create a fresh session token on every (re)connect. | |
| PERMISSIONS | |
| getUserMedia requires a secure context: HTTPS or http://localhost. | |
| Microphone permission is per-origin and must be granted by the user. | |
| ERROR RECOVERY | |
| - On RTCPeerConnection close/fail: stop local tracks, show retry button, | |
| and mint a new session token on the next click. | |
| - On data channel close: attempt reconnect with a new session token. | |
| - On getUserMedia denial: show "Microphone access required". | |
| - On /api/session failure: show "Could not start session — check server config". | |
| WEBRTC FLOW | |
| 1. Click mic → getUserMedia({audio:true}) | |
| 2. fetch /api/session → ephemeral key | |
| 3. new RTCPeerConnection, add mic track | |
| 4. create data channel "oai-events" | |
| 5. createOffer → POST /api/calls?key=ek_... (Content-Type: application/sdp) | |
| 6. setRemoteDescription(answer) | |
| 7. audio flows both ways; transcripts arrive on the data channel | |
| ========================================================================== | |
| */ | |
| *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } | |
| :root { | |
| --bg: #0d1117; | |
| --card: #1a1a2e; | |
| --accent-area: #16213e; | |
| --text: #e6edf3; | |
| --text-muted: #8b949e; | |
| --accent: #58a6ff; | |
| --green: #3fb950; | |
| --red: #f85149; | |
| --yellow: #d29922; | |
| --blue: #58a6ff; | |
| --user-bubble: #1c3a5f; | |
| --ai-bubble: #2a3a2a; | |
| } | |
| html, body { | |
| height: 100%; | |
| background: var(--bg); | |
| color: var(--text); | |
| font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; | |
| overflow: hidden; | |
| } | |
| body { | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| justify-content: center; | |
| min-height: 100vh; | |
| padding: 16px; | |
| } | |
| .app { | |
| width: 100%; | |
| max-width: 600px; | |
| display: flex; | |
| flex-direction: column; | |
| gap: 20px; | |
| height: 100vh; | |
| max-height: 100vh; | |
| } | |
| /* ---- Header ---- */ | |
| .header { | |
| text-align: center; | |
| padding: 8px 0 0; | |
| flex-shrink: 0; | |
| } | |
| .header h1 { | |
| font-size: 1.6rem; | |
| font-weight: 700; | |
| letter-spacing: -0.02em; | |
| background: linear-gradient(135deg, var(--accent), #a371f7); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| background-clip: text; | |
| } | |
| .header p { | |
| font-size: 0.85rem; | |
| color: var(--text-muted); | |
| margin-top: 4px; | |
| } | |
| /* ---- Mic button area ---- */ | |
| .mic-area { | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| justify-content: center; | |
| gap: 16px; | |
| padding: 20px 0 8px; | |
| flex-shrink: 0; | |
| } | |
| .mic-button { | |
| position: relative; | |
| width: 140px; | |
| height: 140px; | |
| border-radius: 50%; | |
| border: none; | |
| cursor: pointer; | |
| background: linear-gradient(145deg, #2a2a3e, #1a1a2e); | |
| box-shadow: 0 8px 32px rgba(0,0,0,0.4), inset 0 2px 4px rgba(255,255,255,0.06); | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| transition: transform 0.15s ease, background 0.3s ease; | |
| color: var(--text-muted); | |
| } | |
| .mic-button:hover { transform: scale(1.04); } | |
| .mic-button:active { transform: scale(0.96); } | |
| .mic-button svg { width: 52px; height: 52px; } | |
| /* State: idle */ | |
| .mic-button.state-idle { color: #6e7681; } | |
| /* State: connecting (yellow pulse) */ | |
| .mic-button.state-connecting { | |
| color: var(--yellow); | |
| background: linear-gradient(145deg, #3d3520, #2a2410); | |
| animation: pulse-yellow 1.2s ease-in-out infinite; | |
| } | |
| @keyframes pulse-yellow { | |
| 0%, 100% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 0 rgba(210,153,34,0.5), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| 50% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 16px rgba(210,153,34,0), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| } | |
| /* State: connected (green gentle pulse) */ | |
| .mic-button.state-connected { | |
| color: var(--green); | |
| background: linear-gradient(145deg, #1a3d2a, #102818); | |
| animation: pulse-green 2.5s ease-in-out infinite; | |
| } | |
| @keyframes pulse-green { | |
| 0%, 100% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 0 rgba(63,185,80,0.45), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| 50% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 12px rgba(63,185,80,0), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| } | |
| /* State: speaking (blue ripple) */ | |
| .mic-button.state-speaking { | |
| color: var(--blue); | |
| background: linear-gradient(145deg, #1a2d4d, #0f1d33); | |
| animation: ripple-blue 1s ease-in-out infinite; | |
| } | |
| @keyframes ripple-blue { | |
| 0% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 0 rgba(88,166,255,0.6), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| 100% { box-shadow: 0 8px 32px rgba(0,0,0,0.4), 0 0 0 24px rgba(88,166,255,0), inset 0 2px 4px rgba(255,255,255,0.06); } | |
| } | |
| /* State: error (red) */ | |
| .mic-button.state-error { | |
| color: var(--red); | |
| background: linear-gradient(145deg, #4a1a1a, #2d1010); | |
| animation: shake 0.4s ease-in-out; | |
| } | |
| @keyframes shake { | |
| 0%, 100% { transform: translateX(0); } | |
| 25% { transform: translateX(-6px); } | |
| 75% { transform: translateX(6px); } | |
| } | |
| .status-text { | |
| font-size: 0.95rem; | |
| color: var(--text-muted); | |
| text-align: center; | |
| min-height: 1.3em; | |
| transition: color 0.3s ease; | |
| } | |
| .status-text.connecting { color: var(--yellow); } | |
| .status-text.connected { color: var(--green); } | |
| .status-text.speaking { color: var(--blue); } | |
| .status-text.error { color: var(--red); } | |
| /* ---- Waveform ---- */ | |
| .waveform { | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| gap: 4px; | |
| height: 36px; | |
| flex-shrink: 0; | |
| } | |
| .waveform .bar { | |
| width: 4px; | |
| height: 8px; | |
| background: var(--text-muted); | |
| border-radius: 2px; | |
| transition: background 0.3s ease; | |
| } | |
| .waveform.active .bar { background: var(--accent); } | |
| .waveform.active.speaking .bar { background: var(--blue); } | |
| .waveform.active .bar { | |
| animation: wave 0.8s ease-in-out infinite; | |
| } | |
| .waveform .bar:nth-child(1) { animation-delay: 0s; } | |
| .waveform .bar:nth-child(2) { animation-delay: 0.1s; } | |
| .waveform .bar:nth-child(3) { animation-delay: 0.2s; } | |
| .waveform .bar:nth-child(4) { animation-delay: 0.15s; } | |
| .waveform .bar:nth-child(5) { animation-delay: 0.05s; } | |
| .waveform .bar:nth-child(6) { animation-delay: 0.25s; } | |
| .waveform .bar:nth-child(7) { animation-delay: 0.1s; } | |
| .waveform .bar:nth-child(8) { animation-delay: 0.2s; } | |
| .waveform .bar:nth-child(9) { animation-delay: 0.3s; } | |
| .waveform .bar:nth-child(10) { animation-delay: 0.15s; } | |
| @keyframes wave { | |
| 0%, 100% { height: 8px; } | |
| 50% { height: 30px; } | |
| } | |
| /* ---- Transcript panel ---- */ | |
| .transcript-panel { | |
| flex: 1; | |
| background: var(--card); | |
| border: 1px solid rgba(255,255,255,0.06); | |
| border-radius: 14px; | |
| display: flex; | |
| flex-direction: column; | |
| overflow: hidden; | |
| min-height: 0; | |
| } | |
| .transcript-header { | |
| padding: 10px 16px; | |
| font-size: 0.75rem; | |
| text-transform: uppercase; | |
| letter-spacing: 0.08em; | |
| color: var(--text-muted); | |
| border-bottom: 1px solid rgba(255,255,255,0.06); | |
| flex-shrink: 0; | |
| } | |
| .transcript-body { | |
| flex: 1; | |
| overflow-y: auto; | |
| padding: 12px 16px; | |
| display: flex; | |
| flex-direction: column; | |
| gap: 10px; | |
| scroll-behavior: smooth; | |
| } | |
| .transcript-body::-webkit-scrollbar { width: 6px; } | |
| .transcript-body::-webkit-scrollbar-track { background: transparent; } | |
| .transcript-body::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; } | |
| .msg { | |
| max-width: 85%; | |
| padding: 9px 14px; | |
| border-radius: 14px; | |
| font-size: 0.9rem; | |
| line-height: 1.4; | |
| word-wrap: break-word; | |
| animation: fade-in 0.3s ease; | |
| } | |
| @keyframes fade-in { | |
| from { opacity: 0; transform: translateY(6px); } | |
| to { opacity: 1; transform: translateY(0); } | |
| } | |
| .msg.user { | |
| align-self: flex-end; | |
| background: var(--user-bubble); | |
| color: var(--text); | |
| border-bottom-right-radius: 4px; | |
| } | |
| .msg.ai { | |
| align-self: flex-start; | |
| background: var(--ai-bubble); | |
| color: var(--text); | |
| border-bottom-left-radius: 4px; | |
| } | |
| .msg .label { | |
| font-size: 0.65rem; | |
| text-transform: uppercase; | |
| letter-spacing: 0.06em; | |
| opacity: 0.6; | |
| margin-bottom: 2px; | |
| } | |
| .msg.system { | |
| align-self: center; | |
| background: transparent; | |
| color: var(--text-muted); | |
| font-size: 0.8rem; | |
| font-style: italic; | |
| text-align: center; | |
| } | |
| .listening-indicator { | |
| align-self: center; | |
| color: var(--text-muted); | |
| font-size: 0.85rem; | |
| font-style: italic; | |
| display: flex; | |
| align-items: center; | |
| gap: 6px; | |
| padding: 4px 0; | |
| } | |
| .listening-indicator .dots span { | |
| display: inline-block; | |
| width: 5px; height: 5px; | |
| background: var(--text-muted); | |
| border-radius: 50%; | |
| animation: dot-pulse 1.4s infinite ease-in-out; | |
| } | |
| .listening-indicator .dots span:nth-child(2) { animation-delay: 0.2s; } | |
| .listening-indicator .dots span:nth-child(3) { animation-delay: 0.4s; } | |
| @keyframes dot-pulse { | |
| 0%, 80%, 100% { opacity: 0.3; } | |
| 40% { opacity: 1; } | |
| } | |
| .empty-state { | |
| text-align: center; | |
| color: var(--text-muted); | |
| font-size: 0.85rem; | |
| padding: 40px 20px; | |
| line-height: 1.6; | |
| } | |
| .empty-state .icon { font-size: 2rem; margin-bottom: 8px; opacity: 0.4; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="app"> | |
| <!-- Header --> | |
| <div class="header"> | |
| <h1>🌍 World Room</h1> | |
| <p>Talk to your live worldbuilding companion</p> | |
| </div> | |
| <!-- Mic button --> | |
| <div class="mic-area"> | |
| <button class="mic-button state-idle" id="micBtn" aria-label="Toggle conversation"> | |
| <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> | |
| <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/> | |
| <path d="M19 10v2a7 7 0 0 1-14 0v-2"/> | |
| <line x1="12" y1="19" x2="12" y2="23"/> | |
| <line x1="8" y1="23" x2="16" y2="23"/> | |
| </svg> | |
| </button> | |
| <div class="status-text" id="statusText">Click to start</div> | |
| </div> | |
| <!-- Waveform --> | |
| <div class="waveform" id="waveform"> | |
| <div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div> | |
| <div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div> | |
| </div> | |
| <!-- Transcript --> | |
| <div class="transcript-panel"> | |
| <div class="transcript-header">Conversation</div> | |
| <div class="transcript-body" id="transcript"> | |
| <div class="empty-state"> | |
| <div class="icon">🗣️</div> | |
| Click the microphone above to start a voice conversation.<br> | |
| Describe a world, a character, or a conflict — World Room will build on it. | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| ; | |
| /* ==================================================================== | |
| World Room — Frontend logic | |
| ==================================================================== */ | |
| const STATUS = { | |
| IDLE: { cls: "idle", text: "Click to start" }, | |
| CONNECTING: { cls: "connecting", text: "Connecting..." }, | |
| CONNECTED: { cls: "connected", text: "Connected — speak to your worldbuilder" }, | |
| SPEAKING: { cls: "speaking", text: "World Room is speaking..." }, | |
| ERROR: { cls: "error", text: "Connection failed — click to retry" }, | |
| MIC_ERROR: { cls: "error", text: "Microphone access required" }, | |
| SESSION_ERR:{ cls: "error", text: "Could not start session — check server config" }, | |
| }; | |
| // DOM refs | |
| const micBtn = document.getElementById("micBtn"); | |
| const statusText = document.getElementById("statusText"); | |
| const waveform = document.getElementById("waveform"); | |
| const transcriptEl= document.getElementById("transcript"); | |
| // State | |
| let pc = null; // RTCPeerConnection | |
| let dc = null; // data channel "oai-events" | |
| let localStream = null; // MediaStream from getUserMedia | |
| let ephemeralKey = null; | |
| let sessionExpiresAt = null; | |
| let currentState = "idle"; | |
| let isConnected = false; | |
| let isConnecting = false; | |
| /* -------------------------------------------------------------------- | |
| Status / visual helpers | |
| -------------------------------------------------------------------- */ | |
| function setState(key) { | |
| const s = STATUS[key] || STATUS.IDLE; | |
| currentState = key.toLowerCase(); | |
| // Mic button classes | |
| micBtn.className = "mic-button state-" + (s.cls || "idle"); | |
| // Status text | |
| statusText.textContent = s.text; | |
| statusText.className = "status-text " + (s.cls || ""); | |
| // Waveform | |
| if (key === "CONNECTED" || key === "SPEAKING") { | |
| waveform.classList.add("active"); | |
| waveform.classList.toggle("speaking", key === "SPEAKING"); | |
| } else { | |
| waveform.classList.remove("active", "speaking"); | |
| } | |
| } | |
| /* -------------------------------------------------------------------- | |
| Transcript helpers | |
| -------------------------------------------------------------------- */ | |
| function clearEmptyState() { | |
| const empty = transcriptEl.querySelector(".empty-state"); | |
| if (empty) empty.remove(); | |
| } | |
| function addMessage(role, text) { | |
| clearEmptyState(); | |
| removeListeningIndicator(); | |
| const div = document.createElement("div"); | |
| div.className = "msg " + role; | |
| const label = document.createElement("div"); | |
| label.className = "label"; | |
| label.textContent = role === "user" ? "You" : "World Room"; | |
| div.appendChild(label); | |
| const content = document.createElement("div"); | |
| content.textContent = text; | |
| div.appendChild(content); | |
| transcriptEl.appendChild(div); | |
| transcriptEl.scrollTop = transcriptEl.scrollHeight; | |
| } | |
| function updateLastAIMessage(text) { | |
| // Update or append the last AI message bubble | |
| let last = transcriptEl.lastElementChild; | |
| if (!last || !last.classList.contains("ai")) { | |
| addMessage("ai", text); | |
| } else { | |
| const content = last.querySelectorAll("div:not(.label)")[0]; | |
| if (content) content.textContent = text; | |
| } | |
| transcriptEl.scrollTop = transcriptEl.scrollHeight; | |
| } | |
| let listeningEl = null; | |
| function showListeningIndicator() { | |
| if (listeningEl && listeningEl.parentNode) return; | |
| removeListeningIndicator(); | |
| clearEmptyState(); | |
| listeningEl = document.createElement("div"); | |
| listeningEl.className = "listening-indicator"; | |
| listeningEl.innerHTML = 'Listening<span class="dots"><span></span><span></span><span></span></span>'; | |
| transcriptEl.appendChild(listeningEl); | |
| transcriptEl.scrollTop = transcriptEl.scrollHeight; | |
| } | |
| function removeListeningIndicator() { | |
| if (listeningEl && listeningEl.parentNode) listeningEl.parentNode.removeChild(listeningEl); | |
| listeningEl = null; | |
| } | |
| function addSystemMessage(text) { | |
| clearEmptyState(); | |
| removeListeningIndicator(); | |
| const div = document.createElement("div"); | |
| div.className = "msg system"; | |
| div.textContent = text; | |
| transcriptEl.appendChild(div); | |
| transcriptEl.scrollTop = transcriptEl.scrollHeight; | |
| } | |
| /* -------------------------------------------------------------------- | |
| Session token | |
| -------------------------------------------------------------------- */ | |
| async function fetchEphemeralKey() { | |
| const resp = await fetch("/api/session", { method: "POST" }); | |
| if (!resp.ok) { | |
| const txt = await resp.text(); | |
| throw new Error("Session request failed: " + resp.status + " " + txt); | |
| } | |
| const data = await resp.json(); | |
| if (!data.ephemeral_key) throw new Error("No ephemeral_key in response"); | |
| ephemeralKey = data.ephemeral_key; | |
| sessionExpiresAt = data.expires_at; | |
| return ephemeralKey; | |
| } | |
| /* -------------------------------------------------------------------- | |
| WebRTC connection | |
| -------------------------------------------------------------------- */ | |
| async function startConversation() { | |
| if (isConnecting || isConnected) return; | |
| isConnecting = true; | |
| setState("CONNECTING"); | |
| try { | |
| // 1. Microphone | |
| localStream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| // 2. Ephemeral key | |
| await fetchEphemeralKey(); | |
| // 3. RTCPeerConnection | |
| pc = new RTCPeerConnection(); | |
| pc.onconnectionstatechange = onConnectionStateChange; | |
| pc.oniceconnectionstatechange = onIceStateChange; | |
| pc.ontrack = onTrack; | |
| // 4. Add mic track | |
| localStream.getAudioTracks().forEach((t) => pc.addTrack(t, localStream)); | |
| // 5. Data channel for transcript events | |
| dc = pc.createDataChannel("oai-events"); | |
| dc.onopen = onDataChannelOpen; | |
| dc.onmessage = onDataChannelMessage; | |
| dc.onclose = onDataChannelClose; | |
| dc.onerror = onDataChannelError; | |
| // 6. Create offer → POST to server → get answer | |
| const offer = await pc.createOffer(); | |
| await pc.setLocalDescription(offer); | |
| // Wait for ICE gathering to complete for a complete SDP | |
| await waitForIceGathering(pc, 2000); | |
| const sdpAnswer = await postSdpOffer(pc.localDescription.sdp); | |
| // 7. Set remote description | |
| await pc.setRemoteDescription( | |
| new RTCSessionDescription({ type: "answer", sdp: sdpAnswer }) | |
| ); | |
| // Button stays in CONNECTING until the connection actually opens; | |
| // onConnectionStateChange will flip it to CONNECTED. | |
| } catch (err) { | |
| console.error("startConversation error:", err); | |
| handleStartError(err); | |
| } finally { | |
| isConnecting = false; | |
| } | |
| } | |
| function postSdpOffer(sdp) { | |
| return fetch("/api/calls?key=" + encodeURIComponent(ephemeralKey), { | |
| method: "POST", | |
| headers: { "Content-Type": "application/sdp" }, | |
| body: sdp, | |
| }).then(async (resp) => { | |
| if (!resp.ok) { | |
| const txt = await resp.text(); | |
| throw new Error("SDP proxy failed: " + resp.status + " " + txt); | |
| } | |
| return resp.text(); | |
| }); | |
| } | |
| function waitForIceGathering(pc, timeoutMs) { | |
| return new Promise((resolve) => { | |
| if (pc.iceGatheringState === "complete") return resolve(); | |
| let done = false; | |
| const finish = () => { if (!done) { done = true; resolve(); } }; | |
| const t = setTimeout(finish, timeoutMs); | |
| pc.addEventListener("icegatheringstatechange", () => { | |
| if (pc.iceGatheringState === "complete") { clearTimeout(t); finish(); } | |
| }); | |
| }); | |
| } | |
| /* -------------------------------------------------------------------- | |
| RTCPeerConnection event handlers | |
| -------------------------------------------------------------------- */ | |
| function onTrack(event) { | |
| // Remote audio track from the AI | |
| const audioEl = document.createElement("audio"); | |
| audioEl.autoplay = true; | |
| audioEl.srcObject = event.streams[0]; | |
| audioEl.play().catch((e) => console.warn("Remote audio play() blocked:", e)); | |
| } | |
| function onConnectionStateChange() { | |
| console.log("PC connection state:", pc?.connectionState); | |
| const st = pc?.connectionState; | |
| if (st === "connected") { | |
| isConnected = true; | |
| if (currentState !== "speaking") setState("CONNECTED"); | |
| showListeningIndicator(); | |
| } else if (st === "disconnected" || st === "failed" || st === "closed") { | |
| isConnected = false; | |
| if (st === "failed" || st === "closed") { | |
| setState("ERROR"); | |
| cleanup(); | |
| } | |
| } | |
| } | |
| function onIceStateChange() { | |
| console.log("ICE state:", pc?.iceConnectionState); | |
| } | |
| /* -------------------------------------------------------------------- | |
| Data channel event handlers | |
| -------------------------------------------------------------------- */ | |
| function onDataChannelOpen() { | |
| console.log("Data channel oai-events opened"); | |
| } | |
| function onDataChannelMessage(event) { | |
| let msg; | |
| try { msg = JSON.parse(event.data); } catch (e) { return; } | |
| handleRealtimeEvent(msg); | |
| } | |
| function onDataChannelClose() { | |
| console.warn("Data channel closed"); | |
| if (isConnected) { | |
| // Attempt reconnect with a fresh session on next user action | |
| isConnected = false; | |
| setState("ERROR"); | |
| cleanup(); | |
| } | |
| } | |
| function onDataChannelError(e) { | |
| console.error("Data channel error:", e); | |
| } | |
| /* -------------------------------------------------------------------- | |
| Realtime event handling | |
| -------------------------------------------------------------------- */ | |
| let currentAiTranscript = ""; | |
| function handleRealtimeEvent(msg) { | |
| const t = msg.type; | |
| // ---- User speech detected / stopped ---- | |
| if (t === "input_audio_buffer.speech_started") { | |
| removeListeningIndicator(); | |
| setState("CONNECTED"); // user is speaking; AI not speaking | |
| } | |
| if (t === "input_audio_buffer.speech_stopped") { | |
| showListeningIndicator(); | |
| } | |
| // ---- Conversation item created (transcript of user or AI speech) ---- | |
| if (t === "conversation.item.created") { | |
| const item = msg.item || {}; | |
| // User input transcript | |
| if (item.type === "message" && item.role === "user") { | |
| const text = extractTranscriptText(item); | |
| if (text) addMessage("user", text); | |
| } | |
| // AI-generated content item (function_call etc. — usually not transcript) | |
| } | |
| // ---- AI response audio transcript (full) ---- | |
| if (t === "response.audio_transcript.done") { | |
| if (msg.transcript) { | |
| currentAiTranscript = msg.transcript; | |
| updateLastAIMessage(msg.transcript); | |
| } | |
| } | |
| // ---- AI response started ---- | |
| if (t === "response.created") { | |
| currentAiTranscript = ""; | |
| setState("SPEAKING"); | |
| removeListeningIndicator(); | |
| } | |
| // ---- AI response audio delta (streaming audio) ---- | |
| if (t === "response.audio.delta") { | |
| // Indicates AI audio is flowing — keep speaking state | |
| if (currentState !== "speaking") setState("SPEAKING"); | |
| } | |
| // ---- AI response done ---- | |
| if (t === "response.done") { | |
| setState("CONNECTED"); | |
| showListeningIndicator(); | |
| } | |
| // ---- Partial transcript (optional, for live user text) ---- | |
| if (t === "conversation.item.input_audio_transcription.completed") { | |
| if (msg.transcript) addMessage("user", msg.transcript); | |
| } | |
| // ---- Error events ---- | |
| if (t === "error") { | |
| console.error("Realtime error event:", msg); | |
| addSystemMessage("⚠️ " + (msg.error?.message || "Realtime error")); | |
| } | |
| } | |
| function extractTranscriptText(item) { | |
| if (item.content && Array.isArray(item.content)) { | |
| const parts = item.content | |
| .filter((c) => c.type === "text" || c.type === "audio" || c.transcript) | |
| .map((c) => c.transcript || c.text || "") | |
| .filter(Boolean); | |
| return parts.join(" "); | |
| } | |
| return ""; | |
| } | |
| /* -------------------------------------------------------------------- | |
| Cleanup | |
| -------------------------------------------------------------------- */ | |
| function cleanup() { | |
| if (pc) { | |
| try { pc.close(); } catch (e) {} | |
| pc = null; | |
| } | |
| if (localStream) { | |
| localStream.getTracks().forEach((t) => t.stop()); | |
| localStream = null; | |
| } | |
| dc = null; | |
| isConnected = false; | |
| isConnecting = false; | |
| } | |
| /* -------------------------------------------------------------------- | |
| Error handling | |
| -------------------------------------------------------------------- */ | |
| function handleStartError(err) { | |
| console.error(err); | |
| if (err && err.name === "NotAllowedError") { | |
| setState("MIC_ERROR"); | |
| } else if (err && (err.message || "").includes("Session request failed")) { | |
| setState("SESSION_ERR"); | |
| } else { | |
| setState("ERROR"); | |
| } | |
| cleanup(); | |
| } | |
| /* -------------------------------------------------------------------- | |
| Mic button click handler | |
| -------------------------------------------------------------------- */ | |
| micBtn.addEventListener("click", async () => { | |
| if (isConnecting) return; | |
| if (isConnected) { | |
| // Hang up | |
| cleanup(); | |
| setState("IDLE"); | |
| addSystemMessage("Conversation ended."); | |
| return; | |
| } | |
| // Start (or retry) | |
| if (currentState === "error" || currentState === "idle") { | |
| await startConversation(); | |
| } else { | |
| await startConversation(); | |
| } | |
| }); | |
| /* -------------------------------------------------------------------- | |
| Init | |
| -------------------------------------------------------------------- */ | |
| setState("IDLE"); | |
| </script> | |
| </body> | |
| </html> | |