1// Plays part of a recording and reports the playhead position for drawing.
2import { useSyncExternalStore } from "react";
4let ctx: AudioContext | null = null;
5let src: AudioBufferSourceNode | null = null;
6let state: { id: string; t: number } | null = null; // recording id + current time (s)
7let startCtx = 0;
8let from = 0;
9let to = 0;
10let raf = 0;
11const listeners = new Set<() => void>();
12const emit = () => listeners.forEach((l) => l());
14function tick() {
15 if (!ctx || !state) return;
16 const t = from + (ctx.currentTime - startCtx);
17 if (t >= to) {
18 stop();
19 return;
20 }
21 state = { id: state.id, t };
22 emit();
23 raf = requestAnimationFrame(tick);
24}
26export function play(id: string, x: Float32Array, fs: number, a: number, b: number) {
27 stop();
28 ctx ??= new AudioContext();
29 const s = Math.max(0, Math.floor(a * fs));
30 const e = Math.min(x.length, Math.ceil(b * fs));
31 if (e <= s) return;
32 const buf = ctx.createBuffer(1, e - s, fs);
33 buf.copyToChannel(x.subarray(s, e) as Float32Array<ArrayBuffer>, 0);
34 src = ctx.createBufferSource();
35 src.buffer = buf;
36 src.connect(ctx.destination);
37 void ctx.resume();
38 startCtx = ctx.currentTime + 0.02;
39 src.start(startCtx);
40 from = s / fs;
41 to = e / fs;
42 state = { id, t: from };
43 emit();
44 raf = requestAnimationFrame(tick);
45}
47export function stop() {
48 cancelAnimationFrame(raf);
49 try {
50 src?.stop();
51 } catch {
52 /* not started */
53 }
54 src = null;
55 if (state) {
56 state = null;
57 emit();
58 }
59}
61const subscribe = (l: () => void) => {
62 listeners.add(l);
63 return () => listeners.delete(l);
64};
66// Playhead time for this recording, or null when it is not playing.
67export function usePlayhead(id: string): number | null {
68 const s = useSyncExternalStore(subscribe, () => state);
69 return s && s.id === id ? s.t : null;
70}