// One shared AudioContext for the whole album, created on the first user gesture. It runs at the // rate performances are computed at (48 kHz) on every device; the browser resamples if needed. import { SAMPLE_RATE } from "../stream/protocol.ts"; export interface AudioEngine { ctx: AudioContext; /** Compositions connect here. */ input: AudioNode; } let engine: AudioEngine | null = null; export async function getAudio(): Promise { if (!engine) { let ctx: AudioContext; try { ctx = new AudioContext({ latencyHint: "playback", sampleRate: SAMPLE_RATE }); } catch { ctx = new AudioContext({ latencyHint: "playback" }); // very old browsers: the player resamples nothing, pitch may differ } const input = ctx.createGain(); // gentle safety limiter on the master bus const limiter = ctx.createDynamicsCompressor(); limiter.threshold.value = -6; limiter.knee.value = 6; limiter.ratio.value = 12; limiter.attack.value = 0.003; limiter.release.value = 0.25; input.connect(limiter).connect(ctx.destination); engine = { ctx, input }; if (import.meta.env.DEV) (globalThis as { __audioEngine?: AudioEngine }).__audioEngine = engine; // for tests in the dev server } if (engine.ctx.state !== "running") await engine.ctx.resume(); return engine; } export function dbToGain(db: number): number { return Math.pow(10, db / 20); }