// Lookahead scheduler (setInterval + ctx.currentTime) with crossfades between tracks. import { getCtx, getMusicBus } from './context'; import { TRACKS } from './tracks'; import type { TrackDef } from './tracks'; import type { Track } from './types'; interface Active { def: TrackDef; out: GainNode; step: number; next: number; sd: number; fadeEnd: number } const LOOKAHEAD = 0.6; // long lookahead: music keeps playing smoothly when the phone's main thread is busy const BACKLOG = 1.2; const FADE = 0.8; let want: Track | null = null; let playing: Track | null = null; let cur: Active | null = null; let fading: Active[] = []; let timer: number | null = null; function run(a: Active, now: number): void { if (a.next < now - BACKLOG) { // tab was hidden / main thread stalled: skip, don't pile up notes const skip = Math.ceil((now - a.next) / a.sd); a.step += skip; a.next += skip * a.sd; } while (a.next < now + LOOKAHEAD) { a.def.step(a.step, a.next, a.out); a.step++; a.next += a.sd; } } function tick(): void { const ctx = getCtx(); if (!ctx) return; const now = ctx.currentTime; if (cur) run(cur, now); fading = fading.filter((a) => { if (now <= a.fadeEnd) return true; a.out.disconnect(); return false; }); if (!cur && !fading.length && timer !== null) { window.clearInterval(timer); timer = null; } } function fadeOut(a: Active, now: number, dur: number): void { a.out.gain.cancelScheduledValues(now); a.out.gain.setValueAtTime(a.out.gain.value, now); a.out.gain.linearRampToValueAtTime(0, now + dur); a.fadeEnd = now + dur + 0.1; fading.push(a); } /** Make the playing track match the wanted one. Safe before init (waits for context). */ export function syncMusic(): void { const ctx = getCtx(), bus = getMusicBus(); if (!ctx || !bus || playing === want) return; const now = ctx.currentTime; if (cur) { fadeOut(cur, now, want ? FADE : 0.5); cur = null; } playing = want; if (want) { const def = TRACKS[want]; const out = ctx.createGain(); out.gain.setValueAtTime(0, now); out.gain.linearRampToValueAtTime(def.level, now + FADE); out.connect(bus); cur = { def, out, step: 0, next: now + 0.06, sd: 60 / def.bpm / def.spb, fadeEnd: 0 }; } if (timer === null && (cur || fading.length)) timer = window.setInterval(tick, 60); tick(); } /** After the context was rebuilt: forget old nodes and start the wanted track again. */ export function resetMusic(): void { cur = null; fading = []; playing = null; if (timer !== null) { window.clearInterval(timer); timer = null; } syncMusic(); } export function startMusic(name: Track): void { if (name === want) return; want = name; syncMusic(); } export function stopMusic(): void { want = null; syncMusic(); }