75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 1// One shared AudioContext for the whole album, created on the first user gesture. It runs at the
2// rate performances are computed at (48 kHz) on every device; the browser resamples if needed.
3import { SAMPLE_RATE } from "../stream/protocol.ts";
5export interface AudioEngine {
6 ctx: AudioContext;
7 /** Compositions connect here. */
8 input: AudioNode;
9}
11let engine: AudioEngine | null = null;
13export async function getAudio(): Promise<AudioEngine> {
14 if (!engine) {
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 15 let ctx: AudioContext;
16 try {
17 ctx = new AudioContext({ latencyHint: "playback", sampleRate: SAMPLE_RATE });
18 } catch {
19 ctx = new AudioContext({ latencyHint: "playback" }); // very old browsers: the player resamples nothing, pitch may differ
20 }
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 21 const input = ctx.createGain();
22 // gentle safety limiter on the master bus
23 const limiter = ctx.createDynamicsCompressor();
24 limiter.threshold.value = -6;
25 limiter.knee.value = 6;
26 limiter.ratio.value = 12;
27 limiter.attack.value = 0.003;
28 limiter.release.value = 0.25;
29 input.connect(limiter).connect(ctx.destination);
30 engine = { ctx, input };
75ca48aOverhaul playback: background-computed, buffered, one clockJeremy Magland 31 if (import.meta.env.DEV) (globalThis as { __audioEngine?: AudioEngine }).__audioEngine = engine; // for tests in the dev server
33 if (engine.ctx.state !== "running") await engine.ctx.resume();
34 return engine;
35}
37export function dbToGain(db: number): number {
38 return Math.pow(10, db / 20);
39}