import type { SpeakerPort } from '../core/controller.ts'; /** * Plays an answer's audio through the page's sound engine (Web Audio). Where it is heard is * Android's choice, not ours: whatever output is selected (earbuds, car, or the phone itself). * The page cannot tell which, so speech is only ever played after the user switched Voice on. * * Device evidence (docs/evidence/device/2026-11-29.md): in the Even app on Dan's phone a page * may play sound without a touch, and did so 20 s after a press. Playing an MP3 this way has * NOT been tried in any real browser or on the device; the tests use a fake sound engine. */ export function createSpeaker(win: Window): SpeakerPort | null { const w = win as unknown as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }; const Ctor = w.AudioContext ?? w.webkitAudioContext; if (!Ctor) return null; let context: AudioContext | null = null; /** * Counts every play() and every stop(). A play() that finds a different number when one of * its waits is over has been stopped or replaced, and must not start (or touch) anything. */ let generation = 0; let current: { source: AudioBufferSourceNode; done: () => void } | null = null; /** Silence whatever is sounding. Does not by itself invalidate work still in progress. */ const silence = () => { const playing = current; current = null; if (!playing) return; try { playing.source.onended = null; playing.source.stop(); } catch { // Already stopped. } playing.done(); }; return { async play(audio: Uint8Array): Promise { // A new play replaces the old one, whatever stage that had reached. const mine = ++generation; silence(); context ??= new Ctor(); const ctx = context; await Promise.race([ctx.resume(), new Promise((r) => win.setTimeout(r, 800))]); if (mine !== generation) return; if (ctx.state !== 'running') throw new Error(`sound is blocked (${ctx.state})`); // decodeAudioData takes ownership of the buffer it is given: hand it a copy. const copy = audio.buffer.slice(audio.byteOffset, audio.byteOffset + audio.byteLength) as ArrayBuffer; const buffer = await ctx.decodeAudioData(copy); // Stopped, or replaced by a newer answer, while decoding: nothing is created or started. if (mine !== generation) return; const source = ctx.createBufferSource(); source.buffer = buffer; source.connect(ctx.destination); await new Promise((resolve) => { current = { source, done: resolve }; source.onended = () => { if (current?.source === source) current = null; resolve(); }; source.start(); }); }, stop(): void { generation += 1; silence(); }, }; }