// Shared AudioContext, bus graph and tiny synth primitives (tone / noise). let ctx: AudioContext | null = null; let master: GainNode | null = null; let sfxBus: GainNode | null = null; let musicBus: GainNode | null = null; let noiseBuf: AudioBuffer | null = null; // Voice limit by end time: a voice can never leak, even if onended does not fire. const voiceEnds: number[] = []; const MAX_VOICES = 14; const vols = { master: 0.7, music: 0.7, sfx: 0.8 }; export const getCtx = (): AudioContext | null => ctx; export const getSfxBus = (): GainNode | null => sfxBus; export const getMusicBus = (): GainNode | null => musicBus; export const canPlay = (): boolean => { if (!ctx) return false; const now = ctx.currentTime; for (let i = voiceEnds.length - 1; i >= 0; i--) if (voiceEnds[i] < now) voiceEnds.splice(i, 1); return voiceEnds.length < MAX_VOICES; }; /** Throw away a broken context (iOS can leave one stuck after an interruption). */ export function dropContext(): void { try { if (ctx && ctx.state !== 'closed') void ctx.close().catch(() => undefined); } catch { /* ignore */ } ctx = null; master = null; sfxBus = null; musicBus = null; noiseBuf = null; voiceEnds.length = 0; } export const rnd = (a: number, b: number): number => a + Math.random() * (b - a); export const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x)); export const midi = (m: number): number => 440 * Math.pow(2, (m - 69) / 12); /** Create context + graph (master -> compressor -> destination). Only call from init(). */ export function createContext(): AudioContext | null { if (ctx) return ctx; const AC = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; if (!AC) return null; try { ctx = new AC({ latencyHint: 'playback' }); } catch { try { ctx = new AC(); } catch { return null; } } master = ctx.createGain(); const comp = ctx.createDynamicsCompressor(); comp.threshold.value = -20; comp.knee.value = 18; comp.ratio.value = 6; comp.attack.value = 0.006; comp.release.value = 0.2; sfxBus = ctx.createGain(); musicBus = ctx.createGain(); sfxBus.connect(master); musicBus.connect(master); master.connect(comp); comp.connect(ctx.destination); master.gain.value = vols.master; musicBus.gain.value = vols.music; sfxBus.gain.value = vols.sfx; noiseBuf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate); const d = noiseBuf.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; return ctx; } export function setBusVolumes(m: number, mu: number, s: number): void { vols.master = clamp(m, 0, 1); vols.music = clamp(mu, 0, 1); vols.sfx = clamp(s, 0, 1); if (!ctx || !master || !musicBus || !sfxBus) return; const t = ctx.currentTime; master.gain.setTargetAtTime(vols.master, t, 0.04); musicBus.gain.setTargetAtTime(vols.music, t, 0.04); sfxBus.gain.setTargetAtTime(vols.sfx, t, 0.04); } /** Count a source as an active voice and free its nodes when it ends. */ export function trackVoice(src: AudioScheduledSourceNode, nodes: AudioNode[], counted = true): void { if (counted && ctx) voiceEnds.push(ctx.currentTime + 2); src.onended = () => { src.disconnect(); for (const n of nodes) n.disconnect(); }; } export interface Mod { rate: number; depth: number } interface Common { t?: number; dur: number; vol?: number; atk?: number; pan?: number; am?: Mod; music?: boolean; dest?: AudioNode; } export interface ToneOpts extends Common { f: number; f2?: number; sweep?: number; rel?: number; type?: OscillatorType; detune?: number; lp?: number; vib?: Mod; } export interface NoiseOpts extends Common { f: number; f2?: number; q?: number; type?: BiquadFilterType; } function envelope(c: AudioContext, g: GainNode, t: number, o: Common & { rel?: number }): void { const vol = o.vol ?? 0.3, atk = o.atk ?? 0.005; g.gain.setValueAtTime(0.0001, t); g.gain.linearRampToValueAtTime(vol, t + atk); if (o.rel !== undefined && o.dur - o.rel > atk) g.gain.setValueAtTime(vol, t + o.dur - o.rel); g.gain.exponentialRampToValueAtTime(0.0001, t + o.dur); void c; } /** Wire (optional AM) -> envelope gain -> (optional pan) -> bus. Returns the first node to feed. */ function output(c: AudioContext, t: number, o: Common & { rel?: number }, extra: AudioNode[]): { input: AudioNode; lfo: OscillatorNode | null } { const g = c.createGain(); envelope(c, g, t, o); extra.push(g); let input: AudioNode = g; let lfo: OscillatorNode | null = null; if (o.am) { const amG = c.createGain(); amG.gain.value = 1 - o.am.depth; lfo = c.createOscillator(); lfo.frequency.value = o.am.rate; const lg = c.createGain(); lg.gain.value = o.am.depth; lfo.connect(lg); lg.connect(amG.gain); amG.connect(g); extra.push(amG, lg, lfo); input = amG; } let tail: AudioNode = g; if (o.pan && typeof c.createStereoPanner === 'function') { const p = c.createStereoPanner(); p.pan.value = clamp(o.pan, -1, 1); g.connect(p); extra.push(p); tail = p; } const dest = o.dest ?? (o.music ? musicBus : sfxBus); if (dest) tail.connect(dest); return { input, lfo }; } export function tone(o: ToneOpts): void { const c = ctx; if (!c) return; const t = Math.max(o.t ?? c.currentTime, c.currentTime); const osc = c.createOscillator(); osc.type = o.type ?? 'sine'; osc.frequency.setValueAtTime(o.f, t); if (o.f2 !== undefined) osc.frequency.exponentialRampToValueAtTime(Math.max(1, o.f2), t + o.dur * (o.sweep ?? 1)); if (o.detune) osc.detune.value = o.detune; const nodes: AudioNode[] = []; const out = output(c, t, o, nodes); let head: AudioNode = osc; if (o.lp) { const lp = c.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = o.lp; osc.connect(lp); head = lp; nodes.push(lp); } head.connect(out.input); const end = t + o.dur + 0.05; if (o.vib) { const l = c.createOscillator(); l.frequency.value = o.vib.rate; const lg = c.createGain(); lg.gain.value = o.vib.depth; l.connect(lg); lg.connect(osc.detune); l.start(t); l.stop(end); nodes.push(l, lg); } if (out.lfo) { out.lfo.start(t); out.lfo.stop(end); } trackVoice(osc, nodes, !o.music); osc.start(t); osc.stop(end); } export function noise(o: NoiseOpts): void { const c = ctx; if (!c || !noiseBuf) return; const t = Math.max(o.t ?? c.currentTime, c.currentTime); const src = c.createBufferSource(); src.buffer = noiseBuf; src.loop = true; const f = c.createBiquadFilter(); f.type = o.type ?? 'bandpass'; f.Q.value = o.q ?? 1; f.frequency.setValueAtTime(o.f, t); if (o.f2 !== undefined) f.frequency.exponentialRampToValueAtTime(Math.max(20, o.f2), t + o.dur); const nodes: AudioNode[] = [f]; const out = output(c, t, o, nodes); src.connect(f); f.connect(out.input); const end = t + o.dur + 0.05; if (out.lfo) { out.lfo.start(t); out.lfo.stop(end); } trackVoice(src, nodes, !o.music); src.start(t, Math.random() * 1.5); src.stop(end); } export function getNoiseBuffer(): AudioBuffer | null { return noiseBuf; }