/** * Motor de audio: grafo master/música/sfx, reverb por convolución, compresor, * polifonía, antirrepetición, paneo y música con crossfade. * El grafo (`AudioGraph`) acepta cualquier BaseAudioContext para poder * renderizar sin conexión (OfflineAudioContext) en pruebas. */ import type { AudioService } from '../core/types'; import { makeImpulse, type Ctx } from './synth'; import { FALLBACK_SFX, SFX, SFX_IDS, makeVoice } from './sfx'; import { MUSIC_IDS, MusicPlayer, compileSong } from './music'; const STORE_KEY = 'emojiheroes.audio.volume'; const MAX_VOICES = 24; const REPEAT_GAP = 0.04; const LOOKAHEAD = 0.25; const TICK_MS = 40; export interface Volumes { master: number; music: number; sfx: number } const clamp01 = (v: number): number => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 1); /** Nodos del grafo para un contexto dado. */ export class AudioGraph { readonly master: GainNode; readonly pauseLp: BiquadFilterNode; readonly comp: DynamicsCompressorNode; readonly musicDry: GainNode; readonly musicWet: GainNode; readonly duck: GainNode; readonly sfxDry: GainNode; readonly sfxWet: GainNode; readonly musicIn: GainNode; readonly musicSendIn: GainNode; readonly sfxIn: GainNode; readonly sfxSendIn: GainNode; private voices: number[] = []; private lastPlayed = new Map(); constructor(readonly ctx: Ctx, vol: Volumes) { const c = ctx; this.comp = c.createDynamicsCompressor(); this.comp.threshold.value = -12; this.comp.knee.value = 8; this.comp.ratio.value = 6; this.comp.attack.value = 0.003; this.comp.release.value = 0.2; this.master = c.createGain(); this.pauseLp = c.createBiquadFilter(); this.pauseLp.type = 'lowpass'; this.pauseLp.frequency.value = 20000; this.pauseLp.Q.value = 0.5; this.pauseLp.connect(this.comp); this.comp.connect(this.master); this.master.connect(c.destination); const reverb = c.createConvolver(); reverb.buffer = makeImpulse(c); const revOut = c.createGain(); revOut.gain.value = 0.55; reverb.connect(revOut); revOut.connect(this.pauseLp); // música: entrada → ducking → volumen (seco) / envío → volumen (húmedo) → reverb this.duck = c.createGain(); this.musicIn = c.createGain(); this.musicSendIn = c.createGain(); this.musicDry = c.createGain(); this.musicWet = c.createGain(); const duckWet = c.createGain(); this.musicIn.connect(this.duck); this.duck.connect(this.musicDry); this.musicDry.connect(this.pauseLp); this.musicSendIn.connect(duckWet); duckWet.connect(this.musicWet); this.musicWet.connect(reverb); // el ducking también afecta al envío this.duckWet = duckWet; this.sfxIn = c.createGain(); this.sfxSendIn = c.createGain(); this.sfxDry = c.createGain(); this.sfxWet = c.createGain(); this.sfxIn.connect(this.sfxDry); this.sfxDry.connect(this.pauseLp); this.sfxSendIn.connect(this.sfxWet); this.sfxWet.connect(reverb); this.applyVolumes(vol, 0); } private readonly duckWet: GainNode; applyVolumes(v: Volumes, ramp = 0.05): void { const t = this.ctx.currentTime; const set = (p: AudioParam, val: number) => { p.cancelScheduledValues(t); p.setValueAtTime(p.value, t); p.linearRampToValueAtTime(val, t + ramp + 0.001); }; // curva perceptual (cuadrática) set(this.master.gain, v.master * v.master * 0.9); set(this.musicDry.gain, v.music * v.music * 0.8); set(this.musicWet.gain, v.music * v.music * 0.8); set(this.sfxDry.gain, v.sfx * v.sfx); set(this.sfxWet.gain, v.sfx * v.sfx); } setDuck(on: boolean): void { const t = this.ctx.currentTime; for (const g of [this.duck, this.duckWet]) { g.gain.cancelScheduledValues(t); g.gain.setTargetAtTime(on ? 0.45 : 1, t, on ? 0.12 : 0.35); } } setMuffled(on: boolean): void { const t = this.ctx.currentTime; const f = this.pauseLp.frequency; f.cancelScheduledValues(t); f.setTargetAtTime(on ? 650 : 20000, t, on ? 0.08 : 0.2); } /** * Dispara un efecto en `when` (por defecto ahora). Devuelve la duración o 0 si se descartó. * `pan` -1..1. No lanza nunca. */ playSfx(id: string, opts: { volume?: number; pitch?: number; pan?: number } = {}, when?: number): number { const c = this.ctx; const now = c.currentTime; const t0 = Math.max(now, when ?? now) + 0.005; let def = SFX[id]; if (!def) { console.debug(`[audio] sfx desconocido: ${id}`); def = FALLBACK_SFX; } const last = this.lastPlayed.get(id); if (last !== undefined && t0 - last < REPEAT_GAP && t0 >= last) return 0; this.voices = this.voices.filter((e) => e > now); if (this.voices.length >= MAX_VOICES) return 0; this.lastPlayed.set(id, t0); const vol = Math.max(0, opts.volume ?? 1); if (vol <= 0) return 0; const pitch = Math.max(0.25, Math.min(4, opts.pitch ?? 1)) * (1 + (Math.random() * 2 - 1) * def.vary); const g = c.createGain(); g.gain.value = vol; let out: AudioNode = g; if (opts.pan && Math.abs(opts.pan) > 0.01) { const p = c.createStereoPanner(); p.pan.value = Math.max(-1, Math.min(1, opts.pan)); g.connect(p); out = p; } out.connect(this.sfxIn); let send: GainNode | null = null; if (def.rev > 0) { send = c.createGain(); send.gain.value = def.rev; out.connect(send); send.connect(this.sfxSendIn); } const dur = def.fn(makeVoice(c, g, t0, pitch)) / pitch; this.voices.push(t0 + dur); if (typeof window !== 'undefined' && c instanceof AudioContext) { setTimeout(() => { try { out.disconnect(); if (out !== g) g.disconnect(); send?.disconnect(); } catch { /* nada */ } }, (t0 - now + dur + 1) * 1000); } return dur; } createPlayer(id: string, startAt: number): MusicPlayer | null { const cs = compileSong(id); if (!cs) return null; return new MusicPlayer(this.ctx, id, cs, this.musicIn, this.musicSendIn, startAt); } } /** Implementación de AudioService para el juego. */ export class AudioEngine implements AudioService { ctx: AudioContext | null = null; graph: AudioGraph | null = null; private vol: Volumes = { master: 1, music: 0.7, sfx: 1 }; readonly volume: Volumes; /** Id pedido (aunque aún no haya contexto). */ private wanted: string | null = null; private wantedFade = 1; private current: MusicPlayer | null = null; /** Tema al que volver tras un tema sin bucle (victory). */ private resumeId: string | null = null; private timer: ReturnType | null = null; private hidden = false; /** Devuelve la x de la cámara para paneo. */ camX: () => number = () => 0; constructor() { this.loadVolumes(); const self = this; const vol = {} as Volumes; for (const k of ['master', 'music', 'sfx'] as const) { Object.defineProperty(vol, k, { enumerable: true, get: () => self.vol[k], set: (v: number) => { self.vol[k] = clamp01(v); self.graph?.applyVolumes(self.vol); self.saveVolumes(); }, }); } this.volume = vol; if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => this.onVisibility()); this.hidden = document.hidden; } } private loadVolumes(): void { try { const raw = localStorage.getItem(STORE_KEY); if (!raw) return; const v = JSON.parse(raw) as Partial; for (const k of ['master', 'music', 'sfx'] as const) if (typeof v[k] === 'number') this.vol[k] = clamp01(v[k]!); } catch { /* sin almacenamiento */ } } private saveVolumes(): void { try { localStorage.setItem(STORE_KEY, JSON.stringify(this.vol)); } catch { /* sin almacenamiento */ } } unlock(): void { try { if (!this.ctx) { const AC: typeof AudioContext | undefined = (globalThis as any).AudioContext ?? (globalThis as any).webkitAudioContext; if (!AC) return; this.ctx = new AC({ latencyHint: 'interactive' }); this.graph = new AudioGraph(this.ctx, this.vol); this.timer = setInterval(() => this.tick(), TICK_MS); if (this.wanted) this.startMusic(this.wanted, this.wantedFade); } if (this.ctx.state !== 'running' && !this.hidden) void this.ctx.resume().catch(() => {}); } catch (err) { console.warn('[audio] no se pudo iniciar Web Audio', err); } } private onVisibility(): void { this.hidden = document.hidden; const ctx = this.ctx; if (!ctx) return; try { if (this.hidden) void ctx.suspend().catch(() => {}); else void ctx.resume().catch(() => {}); } catch { /* nada */ } } sfx(id: string, opts?: { volume?: number; pitch?: number; x?: number }): void { if (id === 'error') return; // el sonido de error molesta: los avisos (toast) ya informan const g = this.graph; if (!g || !this.ctx || this.ctx.state !== 'running') return; try { let pan = 0; if (opts?.x !== undefined && Number.isFinite(opts.x)) { pan = Math.max(-1, Math.min(1, (opts.x - this.camX()) / 13)) * 0.75; } g.playSfx(id, { volume: opts?.volume, pitch: opts?.pitch, pan }); } catch (err) { console.debug('[audio] error en sfx', id, err); } } music(id: string | null, fadeSeconds = 1): void { try { if (id !== null && !compileSong(id)) { console.debug(`[audio] música desconocida: ${id}`); return; } const fade = Math.max(0, fadeSeconds); if (id === 'victory' && this.wanted !== 'victory') this.resumeId = this.wanted; else if (id !== 'victory') this.resumeId = null; if (id === this.wanted && (this.current || !this.ctx)) return; this.wanted = id; this.wantedFade = fade; if (this.ctx && this.graph) this.startMusic(id, fade); } catch (err) { console.debug('[audio] error en music', id, err); } } /** Id del tema que suena (o que sonará al desbloquear). */ get playing(): string | null { return this.wanted; } private startMusic(id: string | null, fade: number): void { const ctx = this.ctx!; const now = ctx.currentTime; if (this.current) { this.current.stop(now, fade); this.current = null; } if (!id) return; const p = this.graph!.createPlayer(id, now + 0.08); if (!p) return; p.fadeIn(now, fade > 0.05 && id !== 'victory' ? fade : 0); this.current = p; p.schedule(now + LOOKAHEAD); } private tick(): void { const ctx = this.ctx; if (!ctx || ctx.state !== 'running') return; const p = this.current; if (!p) return; p.schedule(ctx.currentTime + LOOKAHEAD); if (p.done && ctx.currentTime >= p.endTime) { // tema sin bucle terminado: vuelve al anterior this.current = null; const back = this.resumeId; this.resumeId = null; this.wanted = null; if (back) this.music(back, 1.5); } } setDuck(on: boolean): void { this.graph?.setDuck(on); } setMuffled(on: boolean): void { this.graph?.setMuffled(on); } /** Detiene todo (pruebas). */ dispose(): void { if (this.timer) clearInterval(this.timer); this.timer = null; void this.ctx?.close().catch(() => {}); this.ctx = null; this.graph = null; this.current = null; } } // ───────────────────────────── Análisis sin conexión ───────────────────────────── export interface RenderStats { id: string; peak: number; rms: number; /** Duración total renderizada y último instante audible (> -60 dB). */ seconds: number; audibleUntil: number; ok: boolean; } function stats(id: string, buf: AudioBuffer): RenderStats { let peak = 0; let sum = 0; let lastLoud = 0; const n = buf.length; for (let ch = 0; ch < buf.numberOfChannels; ch++) { const d = buf.getChannelData(ch); for (let i = 0; i < n; i++) { const a = Math.abs(d[i]); if (a > peak) peak = a; sum += d[i] * d[i]; if (a > 0.001 && i > lastLoud) lastLoud = i; } } const rms = Math.sqrt(sum / (n * buf.numberOfChannels)); return { id, peak: +peak.toFixed(3), rms: +rms.toFixed(4), seconds: +(n / buf.sampleRate).toFixed(2), audibleUntil: +(lastLoud / buf.sampleRate).toFixed(2), ok: peak >= 0.05 && peak <= 1, }; } const DEFAULT_VOL: Volumes = { master: 1, music: 0.7, sfx: 1 }; /** Renderiza un sfx sin conexión y devuelve pico/rms/duración. */ export async function renderSfx(id: string, seconds = 2.5, vol: Volumes = DEFAULT_VOL): Promise { const ctx = new OfflineAudioContext(2, Math.ceil(44100 * seconds), 44100); const g = new AudioGraph(ctx, vol); g.playSfx(id, {}, 0); return stats(id, await ctx.startRendering()); } /** Renderiza `seconds` de un tema sin conexión. */ export async function renderMusic(id: string, seconds = 8, vol: Volumes = DEFAULT_VOL): Promise { const ctx = new OfflineAudioContext(2, Math.ceil(44100 * seconds), 44100); const g = new AudioGraph(ctx, vol); const p = g.createPlayer(id, 0); if (!p) throw new Error(`música desconocida: ${id}`); p.schedule(seconds); return stats(id, await ctx.startRendering()); } /** Batería completa de pruebas numéricas. */ export async function analyzeAll(musicSeconds = 8): Promise<{ sfx: RenderStats[]; music: RenderStats[] }> { const sfx: RenderStats[] = []; for (const id of SFX_IDS) sfx.push(await renderSfx(id)); const music: RenderStats[] = []; for (const id of MUSIC_IDS) music.push(await renderMusic(id, musicSeconds)); return { sfx, music }; }