// Plays part of a recording and reports the playhead position for drawing. import { useSyncExternalStore } from "react"; let ctx: AudioContext | null = null; let src: AudioBufferSourceNode | null = null; let state: { id: string; t: number } | null = null; // recording id + current time (s) let startCtx = 0; let from = 0; let to = 0; let raf = 0; const listeners = new Set<() => void>(); const emit = () => listeners.forEach((l) => l()); function tick() { if (!ctx || !state) return; const t = from + (ctx.currentTime - startCtx); if (t >= to) { stop(); return; } state = { id: state.id, t }; emit(); raf = requestAnimationFrame(tick); } export function play(id: string, x: Float32Array, fs: number, a: number, b: number) { stop(); ctx ??= new AudioContext(); const s = Math.max(0, Math.floor(a * fs)); const e = Math.min(x.length, Math.ceil(b * fs)); if (e <= s) return; const buf = ctx.createBuffer(1, e - s, fs); buf.copyToChannel(x.subarray(s, e) as Float32Array, 0); src = ctx.createBufferSource(); src.buffer = buf; src.connect(ctx.destination); void ctx.resume(); startCtx = ctx.currentTime + 0.02; src.start(startCtx); from = s / fs; to = e / fs; state = { id, t: from }; emit(); raf = requestAnimationFrame(tick); } export function stop() { cancelAnimationFrame(raf); try { src?.stop(); } catch { /* not started */ } src = null; if (state) { state = null; emit(); } } const subscribe = (l: () => void) => { listeners.add(l); return () => listeners.delete(l); }; // Playhead time for this recording, or null when it is not playing. export function usePlayhead(id: string): number | null { const s = useSyncExternalStore(subscribe, () => state); return s && s.id === id ? s.t : null; }