Files
collina-binaurals/web/audio-engine.js
T
Jorem Juárez 1a6977a59e feat(ios): fase 4 — Media Session, keep-alive, pausa y ajustes AirPods
- pausar/reanudar vía ctx.suspend(): el reloj de audio se congela y la
  automatización programada queda intacta (nada se reinicia)
- keep-alive: <audio> WAV silencioso en loop, arrancado síncrono dentro
  del gesto, para sobrevivir al bloqueo de pantalla en iOS
- Media Session: metadata, play/pause/stop y posición en pantalla de
  bloqueo; controles del tallo del AirPod sincronizados
- detección de oído: eventos pause/play del keep-alive sincronizan la
  sesión sin reiniciarla; interrupciones reflejadas vía onstatechange
- vista Ajustes: checklist de 9 puntos con rutas de iOS (localStorage)
  y test de separación estéreo (L / R / batido)
- guion de pruebas del criterio 11 en docs/pruebas-dispositivo.md
- Playwright: 3 specs en verde (sesión, pausa, ajustes)
2026-08-30 08:03:47 -06:00

297 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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();
/** @type {((estado: string) => void)|null} — cambios de estado del contexto */
this.alEstado = null;
}
/** 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';
this.ctx.onstatechange = () => {
if (this.alEstado) this.alEstado(this.ctx.state);
};
}
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);
}
}
/**
* Pausa congelando el reloj de audio: la automatización ya programada
* queda intacta y la sesión continúa exactamente donde iba al reanudar.
*/
async pausar() {
if (this.ctx && this.nodos && this.ctx.state === 'running') await this.ctx.suspend();
}
/** Reanuda la sesión pausada (o interrumpida por iOS) sin reiniciarla. */
async reanudar() {
if (this.ctx && this.nodos && this.ctx.state !== 'running') await this.ctx.resume();
}
/** true mientras hay sesión sonando (o en pre-roll). */
get activa() {
return this.nodos !== null;
}
/** true si hay sesión pero el contexto no corre (pausa o interrupción). */
get pausada() {
return this.nodos !== null && this.ctx !== null && this.ctx.state !== 'running';
}
/**
* Tono corto de prueba para el test de separación estéreo.
* @param {'izquierda'|'derecha'|'binaural'} canal
* @param {{carrier?: number, beat?: number, dur?: number, nivelDb?: number}} [opciones]
* @returns {Promise<void>} se resuelve cuando el tono termina
*/
async tonoDePrueba(canal, { carrier = 250, beat = 10, dur = 3, nivelDb = -20 } = {}) {
await this.asegurarContexto();
const ctx = this.ctx;
const t0 = ctx.currentTime + 0.05;
const tFin = t0 + dur;
const merger = ctx.createChannelMerger(2);
const volumen = ctx.createGain();
volumen.gain.value = Math.pow(10, nivelDb / 20);
merger.connect(volumen).connect(ctx.destination);
const oscs = [];
const agregar = (freq, entrada) => {
const osc = ctx.createOscillator();
osc.type = 'sine';
osc.frequency.value = freq;
const g = ctx.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(AMP_TONO, t0 + 0.05); // sin clicks
g.gain.setValueAtTime(AMP_TONO, tFin - 0.05);
g.gain.linearRampToValueAtTime(0, tFin);
osc.connect(g).connect(merger, 0, entrada);
osc.start(t0);
osc.stop(tFin + 0.05);
oscs.push(osc);
};
if (canal === 'izquierda' || canal === 'binaural') agregar(carrier, 0);
if (canal === 'derecha') agregar(carrier, 1);
if (canal === 'binaural') agregar(carrier + beat, 1);
await new Promise((resolver) => {
oscs[oscs.length - 1].onended = () => resolver(undefined);
});
}
/**
* 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 };
}
}