/** * Primitivas de síntesis: tono con envolvente/barrido/FM/vibrato y ruido filtrado. * Funcionan sobre cualquier BaseAudioContext (tiempo real u OfflineAudioContext). */ export type Ctx = BaseAudioContext; const noiseCache = new WeakMap(); /** Ruido blanco de 2 s, compartido por contexto. */ export function noiseBuffer(ctx: Ctx): AudioBuffer { let b = noiseCache.get(ctx); if (!b) { b = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 2), ctx.sampleRate); const d = b.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; noiseCache.set(ctx, b); } return b; } /** Impulso de reverb corta: ruido estéreo con caída exponencial y algo de filtrado. */ export function makeImpulse(ctx: Ctx, seconds = 1.1, decay = 3.2): AudioBuffer { const len = Math.floor(ctx.sampleRate * seconds); const buf = ctx.createBuffer(2, len, ctx.sampleRate); for (let ch = 0; ch < 2; ch++) { const d = buf.getChannelData(ch); let lp = 0; for (let i = 0; i < len; i++) { const x = i / len; const white = Math.random() * 2 - 1; // el brillo decae más rápido que el cuerpo const k = 0.25 + 0.7 * (1 - x) * (1 - x); lp += (white - lp) * k; const pre = Math.min(1, i / (ctx.sampleRate * 0.004)); d[i] = lp * pre * Math.pow(1 - x, decay); } } return buf; } const clampF = (f: number): number => Math.min(18000, Math.max(20, f)); /** Envolvente: ataque lineal y caída exponencial (percusiva) o mantenida con relajación. */ export function envelope( p: AudioParam, t: number, dur: number, vol: number, a = 0.005, hold = false, r = 0.05, ): void { const att = Math.max(0.001, Math.min(a, dur * 0.5)); p.setValueAtTime(0, t); p.linearRampToValueAtTime(vol, t + att); if (hold) { const rel = Math.max(0.004, Math.min(r, dur - att)); p.setValueAtTime(vol, Math.max(t + att, t + dur - rel)); p.linearRampToValueAtTime(0, t + dur); } else { p.exponentialRampToValueAtTime(Math.max(vol * 0.001, 1e-5), t + dur); p.linearRampToValueAtTime(0, t + dur + 0.015); } } export interface ToneOpts { t: number; dur: number; f: number; vol: number; type?: OscillatorType; /** Barrido exponencial hasta f2 en ft segundos (por defecto dur). */ f2?: number; ft?: number; /** Barrido por tramos: [segundos desde t, frecuencia]. */ fpts?: Array<[number, number]>; a?: number; hold?: boolean; r?: number; /** Vibrato: profundidad relativa (0.01 = 1 %), frecuencia y retardo de entrada. */ vib?: number; vibRate?: number; vibDelay?: number; /** FM: razón de la moduladora, índice y caída del índice. */ fm?: number; fmIndex?: number; fmDecay?: number; /** Paso-bajo opcional con barrido lp → lp2 en lpt segundos. */ lp?: number; lp2?: number; lpt?: number; q?: number; detune?: number; } export function tone(ctx: Ctx, dest: AudioNode, o: ToneOpts): void { const t = o.t; const f = clampF(o.f); const stopAt = t + o.dur + 0.04; const osc = ctx.createOscillator(); osc.type = o.type ?? 'sine'; osc.frequency.setValueAtTime(f, t); if (o.fpts) { for (const [dt, ff] of o.fpts) osc.frequency.exponentialRampToValueAtTime(clampF(ff), t + dt); } else if (o.f2 !== undefined) { osc.frequency.exponentialRampToValueAtTime(clampF(o.f2), t + (o.ft ?? o.dur)); } if (o.detune) osc.detune.value = o.detune; const g = ctx.createGain(); envelope(g.gain, t, o.dur, o.vol, o.a, o.hold, o.r); let last: AudioNode = osc; if (o.lp) { const flt = ctx.createBiquadFilter(); flt.type = 'lowpass'; flt.Q.value = o.q ?? 0.7; flt.frequency.setValueAtTime(clampF(o.lp), t); if (o.lp2 !== undefined) flt.frequency.exponentialRampToValueAtTime(clampF(o.lp2), t + (o.lpt ?? o.dur)); last.connect(flt); last = flt; } last.connect(g); g.connect(dest); if (o.vib) { const lfo = ctx.createOscillator(); lfo.frequency.value = o.vibRate ?? 6; const lg = ctx.createGain(); const depth = f * o.vib; if (o.vibDelay) { lg.gain.setValueAtTime(0, t); lg.gain.linearRampToValueAtTime(depth, t + o.vibDelay); } else { lg.gain.value = depth; } lfo.connect(lg); lg.connect(osc.frequency); lfo.start(t); lfo.stop(stopAt); } if (o.fm) { const mod = ctx.createOscillator(); mod.frequency.value = clampF(f * o.fm); const mg = ctx.createGain(); const idx = f * (o.fmIndex ?? 1); mg.gain.setValueAtTime(idx, t); mg.gain.exponentialRampToValueAtTime(Math.max(idx * 0.01, 0.01), t + (o.fmDecay ?? o.dur)); mod.connect(mg); mg.connect(osc.frequency); mod.start(t); mod.stop(stopAt); } osc.start(t); osc.stop(stopAt); } export interface NoiseOpts { t: number; dur: number; vol: number; a?: number; hold?: boolean; r?: number; type?: BiquadFilterType; f?: number; f2?: number; ft?: number; fpts?: Array<[number, number]>; q?: number; } export function noise(ctx: Ctx, dest: AudioNode, o: NoiseOpts): void { const t = o.t; const src = ctx.createBufferSource(); src.buffer = noiseBuffer(ctx); src.loop = true; const g = ctx.createGain(); envelope(g.gain, t, o.dur, o.vol, o.a ?? 0.003, o.hold, o.r); let last: AudioNode = src; if (o.f) { const flt = ctx.createBiquadFilter(); flt.type = o.type ?? 'lowpass'; flt.Q.value = o.q ?? 0.8; flt.frequency.setValueAtTime(clampF(o.f), t); if (o.fpts) { for (const [dt, ff] of o.fpts) flt.frequency.exponentialRampToValueAtTime(clampF(ff), t + dt); } else if (o.f2 !== undefined) { flt.frequency.exponentialRampToValueAtTime(clampF(o.f2), t + (o.ft ?? o.dur)); } last.connect(flt); last = flt; } last.connect(g); g.connect(dest); src.start(t, Math.random() * 1.5); src.stop(t + o.dur + 0.04); } export const midiToFreq = (m: number): number => 440 * Math.pow(2, (m - 69) / 12);