- audio-engine: 2 osciladores → merger estéreo → envolvente → volumen; ruido en loop compartiendo envolvente; automatización completa programada de una vez sobre el reloj de audio - misma escala −3 dBFS y misma forma de fades que el export - timer sobre ctx.currentTime − outputLatency (no setTimeout) - indicador de batido/banda (alpha·beta·transición) interpolando el schedule - Playwright (criterio 10) en verde con servidor real
236 lines
8.2 KiB
JavaScript
236 lines
8.2 KiB
JavaScript
/**
|
||
* Motor Web Audio: renderizador delgado del schedule que entrega el backend.
|
||
*
|
||
* Toda la lógica de sesión (curva de batido, pre-roll, fades) viene en el
|
||
* schedule; aquí solo se programa de una vez sobre el reloj de audio, de
|
||
* modo que la sesión sobrevive aunque la UI se congele o la pantalla se
|
||
* bloquee. Sin ningún procesamiento estéreo: L y R solo difieren en
|
||
* frecuencia.
|
||
*/
|
||
|
||
const AMP_TONO = 0.5;
|
||
const PICO_MAX = Math.pow(10, -3 / 20); // −3 dBFS, igual que el export
|
||
|
||
/**
|
||
* @typedef {{t: number, beat_hz: number}} Punto
|
||
* @typedef {{carrier_hz: number, fade_s: number, noise: string, noise_db: number,
|
||
* duration_s: number, preroll_s: number, points: Punto[]}} Schedule
|
||
*/
|
||
|
||
/** @param {AudioBuffer} buffer */
|
||
function picoDeBuffer(buffer) {
|
||
let pico = 0;
|
||
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||
const datos = buffer.getChannelData(c);
|
||
for (let i = 0; i < datos.length; i++) {
|
||
const v = Math.abs(datos[i]);
|
||
if (v > pico) pico = v;
|
||
}
|
||
}
|
||
return pico;
|
||
}
|
||
|
||
export class MotorBinaural {
|
||
constructor() {
|
||
/** @type {AudioContext|null} */
|
||
this.ctx = null;
|
||
/** @type {object|null} nodos vivos de la sesión en curso */
|
||
this.nodos = null;
|
||
/** @type {Schedule|null} */
|
||
this.schedule = null;
|
||
this.tInicio = 0; // reloj de audio: t=0 de la sesión (tras el pre-roll)
|
||
this.tFin = 0;
|
||
/** @type {Map<string, AudioBuffer>} */
|
||
this._ruidos = new Map();
|
||
}
|
||
|
||
/** Crea/reanuda el AudioContext. Debe llamarse dentro del gesto del usuario. */
|
||
async asegurarContexto() {
|
||
if (!this.ctx) {
|
||
const Ctor = window.AudioContext || window.webkitAudioContext;
|
||
this.ctx = new Ctor(); // sin forzar sampleRate: usar el nativo
|
||
if (navigator.audioSession) navigator.audioSession.type = 'playback';
|
||
}
|
||
if (this.ctx.state === 'suspended') await this.ctx.resume();
|
||
if (this.ctx.state !== 'running') {
|
||
throw new Error('El navegador bloqueó el audio. Toca Iniciar de nuevo.');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Descarga y decodifica el loop de ruido del backend (cacheado en memoria).
|
||
* @param {string} tipo — pink | rain
|
||
* @returns {Promise<AudioBuffer>}
|
||
*/
|
||
async cargarRuido(tipo) {
|
||
const sr = [44100, 48000].includes(this.ctx.sampleRate) ? this.ctx.sampleRate : 44100;
|
||
const clave = `${tipo}-${sr}`;
|
||
if (this._ruidos.has(clave)) return this._ruidos.get(clave);
|
||
const resp = await fetch(`/api/noise/${tipo}.wav?sr=${sr}`);
|
||
if (!resp.ok) throw new Error(`No pude descargar el ruido ${tipo} (${resp.status}).`);
|
||
const buffer = await this.ctx.decodeAudioData(await resp.arrayBuffer());
|
||
this._ruidos.set(clave, buffer);
|
||
return buffer;
|
||
}
|
||
|
||
/**
|
||
* Arranca la sesión: construye el grafo y programa TODA la automatización
|
||
* (batido, fades, stop) de una vez con el reloj de audio.
|
||
* @param {Schedule} schedule
|
||
* @param {{volumenDb?: number, alTerminar?: (() => void)|null}} [opciones]
|
||
*/
|
||
async iniciar(schedule, { volumenDb = -20, alTerminar = null } = {}) {
|
||
await this.asegurarContexto();
|
||
if (this.nodos) this.detener();
|
||
const ctx = this.ctx;
|
||
this.schedule = schedule;
|
||
|
||
let bufferRuido = null;
|
||
if (schedule.noise !== 'none') bufferRuido = await this.cargarRuido(schedule.noise);
|
||
|
||
const t0 = ctx.currentTime + 0.15;
|
||
const tInicio = t0 + schedule.preroll_s;
|
||
const tFin = tInicio + schedule.duration_s;
|
||
|
||
// Tono binaural: un oscilador por oído → merger estéreo.
|
||
const merger = ctx.createChannelMerger(2);
|
||
const oscL = ctx.createOscillator();
|
||
const oscR = ctx.createOscillator();
|
||
oscL.type = oscR.type = 'sine';
|
||
oscL.frequency.value = schedule.carrier_hz;
|
||
const gL = ctx.createGain();
|
||
const gR = ctx.createGain();
|
||
gL.gain.value = gR.gain.value = AMP_TONO;
|
||
oscL.connect(gL).connect(merger, 0, 0);
|
||
oscR.connect(gR).connect(merger, 0, 1);
|
||
|
||
const envolvente = ctx.createGain();
|
||
const volumen = ctx.createGain();
|
||
volumen.gain.value = Math.pow(10, volumenDb / 20);
|
||
merger.connect(envolvente).connect(volumen).connect(ctx.destination);
|
||
|
||
// Ruido en loop → envolvente (comparte pre-roll y fades con el tono).
|
||
let fuenteRuido = null;
|
||
let ganRuido = 0;
|
||
let picoRuido = 0;
|
||
if (bufferRuido) {
|
||
ganRuido = Math.pow(10, schedule.noise_db / 20);
|
||
picoRuido = picoDeBuffer(bufferRuido);
|
||
fuenteRuido = ctx.createBufferSource();
|
||
fuenteRuido.buffer = bufferRuido;
|
||
fuenteRuido.loop = true;
|
||
const gRuido = ctx.createGain();
|
||
gRuido.gain.value = ganRuido;
|
||
fuenteRuido.connect(gRuido).connect(envolvente);
|
||
}
|
||
|
||
// Misma escala determinista que el export: pico ≤ −3 dBFS, nunca clipear.
|
||
const escala = Math.min(1, PICO_MAX / (AMP_TONO + ganRuido * picoRuido));
|
||
|
||
// Curva de batido: los puntos del schedule tal cual, en el oscilador derecho.
|
||
const pts = schedule.points;
|
||
const fr = oscR.frequency;
|
||
fr.setValueAtTime(schedule.carrier_hz + pts[0].beat_hz, t0);
|
||
fr.setValueAtTime(schedule.carrier_hz + pts[0].beat_hz, tInicio + pts[0].t);
|
||
for (let i = 1; i < pts.length; i++) {
|
||
fr.linearRampToValueAtTime(schedule.carrier_hz + pts[i].beat_hz, tInicio + pts[i].t);
|
||
}
|
||
|
||
// Envolvente: silencio en el pre-roll, fades lineales (misma forma que el export).
|
||
const fade = Math.min(schedule.fade_s, schedule.duration_s / 2);
|
||
const e = envolvente.gain;
|
||
e.setValueAtTime(0, t0);
|
||
e.setValueAtTime(0, tInicio);
|
||
e.linearRampToValueAtTime(escala, tInicio + fade);
|
||
e.setValueAtTime(escala, tFin - fade);
|
||
e.linearRampToValueAtTime(0, tFin);
|
||
|
||
const margen = 0.2;
|
||
oscL.start(t0);
|
||
oscR.start(t0);
|
||
oscL.stop(tFin + margen);
|
||
oscR.stop(tFin + margen);
|
||
if (fuenteRuido) {
|
||
fuenteRuido.start(t0);
|
||
fuenteRuido.stop(tFin + margen);
|
||
}
|
||
oscR.onended = () => {
|
||
if (this.nodos) {
|
||
this._limpiar();
|
||
if (alTerminar) alTerminar();
|
||
}
|
||
};
|
||
|
||
this.nodos = { oscL, oscR, fuenteRuido, merger, envolvente, volumen };
|
||
this.tInicio = tInicio;
|
||
this.tFin = tFin;
|
||
}
|
||
|
||
/** Detiene la sesión con un fade corto (sin click). */
|
||
detener() {
|
||
if (!this.ctx || !this.nodos) return;
|
||
const { envolvente, oscL, oscR, fuenteRuido } = this.nodos;
|
||
const ahora = this.ctx.currentTime;
|
||
oscR.onended = null;
|
||
envolvente.gain.cancelScheduledValues(ahora);
|
||
envolvente.gain.setValueAtTime(envolvente.gain.value, ahora);
|
||
envolvente.gain.linearRampToValueAtTime(0, ahora + 0.2);
|
||
for (const nodo of [oscL, oscR, fuenteRuido]) {
|
||
if (nodo) {
|
||
try {
|
||
nodo.stop(ahora + 0.25);
|
||
} catch {
|
||
/* ya estaba detenido */
|
||
}
|
||
}
|
||
}
|
||
const nodos = this.nodos;
|
||
this.nodos = null;
|
||
setTimeout(() => {
|
||
for (const n of Object.values(nodos)) if (n && n.disconnect) n.disconnect();
|
||
}, 400);
|
||
}
|
||
|
||
/** @param {number} db — volumen maestro en dBFS (−60…0) */
|
||
cambiarVolumen(db) {
|
||
if (this.nodos) {
|
||
this.nodos.volumen.gain.setTargetAtTime(Math.pow(10, db / 20), this.ctx.currentTime, 0.05);
|
||
}
|
||
}
|
||
|
||
/** true mientras hay sesión sonando (o en pre-roll). */
|
||
get activa() {
|
||
return this.nodos !== null;
|
||
}
|
||
|
||
/**
|
||
* Segundos de sesión que el oído ya escuchó (negativo durante el pre-roll):
|
||
* reloj de audio menos la latencia de salida, no el reloj del sistema.
|
||
*/
|
||
get tiempoSesion() {
|
||
if (!this.ctx) return 0;
|
||
const latencia = this.ctx.outputLatency || this.ctx.baseLatency || 0;
|
||
return this.ctx.currentTime - latencia - this.tInicio;
|
||
}
|
||
|
||
/**
|
||
* Batido que suena ahora y si está en rampa (solo para pintar la UI:
|
||
* es la misma interpolación lineal de los puntos, no lógica nueva).
|
||
* @returns {{hz: number, enRampa: boolean}}
|
||
*/
|
||
batidoActual() {
|
||
const sch = this.schedule;
|
||
if (!sch) return { hz: 0, enRampa: false };
|
||
const pts = sch.points;
|
||
const t = Math.min(Math.max(this.tiempoSesion, 0), sch.duration_s);
|
||
let i = 0;
|
||
while (i < pts.length - 2 && t >= pts[i + 1].t) i++;
|
||
const a = pts[i];
|
||
const b = pts[Math.min(i + 1, pts.length - 1)];
|
||
if (b.t <= a.t) return { hz: b.beat_hz, enRampa: false };
|
||
const frac = Math.min(Math.max((t - a.t) / (b.t - a.t), 0), 1);
|
||
const hz = a.beat_hz + frac * (b.beat_hz - a.beat_hz);
|
||
return { hz, enRampa: a.beat_hz !== b.beat_hz };
|
||
}
|
||
}
|