// Public audio API. Everything is a safe no-op until init() is called from a user gesture. import { createContext, dropContext, getCtx, setBusVolumes } from './context'; import { iosUnlock, installUnlockListeners, primeContext } from './unlock'; import { playSfx } from './sfx'; import { playMeow } from './meow'; import { resetMusic, startMusic, stopMusic, syncMusic } from './music'; import type { Sfx, Mood, Track, PlayOpts } from './types'; export type { Sfx, Mood, Track, PlayOpts } from './types'; let stuck = 0, needRebuild = false; function rebuildOnGesture(): void { const c = getCtx(); if (!needRebuild || !c || c.state === 'running') { needRebuild = false; return; } needRebuild = false; stuck = 0; try { dropContext(); iosUnlock(); if (createContext()) { primeContext(); resetMusic(); } } catch { /* ignore */ } } if (typeof window !== 'undefined') for (const ev of ['pointerdown', 'touchend', 'keydown']) window.addEventListener(ev, rebuildOnGesture, { capture: true, passive: true }); export const audio = { init(): void { try { const fresh = !getCtx(); iosUnlock(); // set the iOS playback session BEFORE the context exists (changing it later can interrupt audio) if (!createContext()) return; if (fresh) primeContext(); installUnlockListeners(); syncMusic(); } catch { /* audio must never break the game */ } }, play(name: Sfx, opts?: PlayOpts): void { try { playSfx(name, opts); } catch { /* ignore */ } }, meow(voice: number, mood?: Mood, opts?: PlayOpts): void { try { playMeow(voice, mood, opts); } catch { /* ignore */ } }, startMusic(track: Track): void { try { startMusic(track); } catch { /* ignore */ } }, stopMusic(): void { try { stopMusic(); } catch { /* ignore */ } }, setVolumes(master: number, music: number, sfx: number): void { setBusVolumes(master, music, sfx); }, /** Call about once a second: recovers audio that iOS or the browser stopped. */ watchdog(): void { const c = getCtx(); if (!c || document.hidden) { stuck = 0; return; } if (c.state === 'running') { stuck = 0; return; } try { void c.resume().catch(() => undefined); } catch { /* ignore */ } stuck++; if (c.state === 'closed' || stuck > 3) needRebuild = true; // rebuilt on the next tap (iOS needs a gesture) }, /** Sound button: restart audio from scratch inside the tap. */ kick(): void { const c = getCtx(); if (!c) { this.init(); return; } if (c.state === 'running') return; needRebuild = true; rebuildOnGesture(); }, isRunning(): boolean { return getCtx()?.state === 'running'; }, }; if (typeof window !== 'undefined') { // eslint-disable-next-line @typescript-eslint/no-explicit-any (window as any).__fckAudio = { get ctx() { return getCtx(); }, iosUnlock, }; }