- 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)
348 lines
10 KiB
JavaScript
348 lines
10 KiB
JavaScript
/** Navegación, estado y pegamento entre la API y el motor de audio. */
|
||
|
||
import {
|
||
CHECKLIST,
|
||
keepAliveElemento,
|
||
keepAliveIniciar,
|
||
keepAlivePausar,
|
||
keepAliveParar,
|
||
mediaSessionConfigurar,
|
||
mediaSessionEstado,
|
||
mediaSessionLimpiar,
|
||
mediaSessionPosicion,
|
||
} from './airpods.js';
|
||
import { MotorBinaural } from './audio-engine.js';
|
||
import { Temporizador } from './timer.js';
|
||
|
||
const motor = new MotorBinaural();
|
||
const $ = (id) => document.getElementById(id);
|
||
|
||
/** @type {{preset: object, schedule: object}|null} */
|
||
let sesionActual = null;
|
||
|
||
const temporizador = new Temporizador(pintarTic);
|
||
|
||
/* ── Inicio: tarjetas de presets ── */
|
||
|
||
async function cargarPresets() {
|
||
const contenedor = $('lista-presets');
|
||
try {
|
||
const resp = await fetch('/api/presets');
|
||
if (!resp.ok) throw new Error(`API respondió ${resp.status}`);
|
||
const presets = await resp.json();
|
||
contenedor.replaceChildren(...presets.map(tarjetaDe));
|
||
} catch (err) {
|
||
contenedor.innerHTML = `<p class="cargando">No pude cargar los presets: ${err.message}</p>`;
|
||
}
|
||
}
|
||
|
||
/** @param {object} p — tarjeta de /api/presets */
|
||
function tarjetaDe(p) {
|
||
const btn = document.createElement('button');
|
||
btn.className = 'tarjeta';
|
||
btn.type = 'button';
|
||
const rango =
|
||
p.beat_min_hz === p.beat_max_hz
|
||
? `${p.beat_min_hz} Hz`
|
||
: `${p.beat_min_hz}–${p.beat_max_hz} Hz`;
|
||
const bandas = [banda(p.beat_min_hz), banda(p.beat_max_hz)];
|
||
const chipBanda = bandas[0] === bandas[1] ? [bandas[0]] : bandas;
|
||
btn.innerHTML = `
|
||
<h3>${p.name.replace('_', ' ')}</h3>
|
||
<p>${p.description}</p>
|
||
<span class="datos">
|
||
${chipBanda.map((b) => `<span class="chip ${b}">${b}</span>`).join('')}
|
||
<span class="chip">${rango}</span>
|
||
<span class="chip">${p.duracion_min} min</span>
|
||
${p.noise !== 'none' ? `<span class="chip">${p.noise === 'rain' ? 'lluvia' : 'ruido rosa'}</span>` : ''}
|
||
</span>`;
|
||
btn.addEventListener('click', () => abrirSesion(p.name));
|
||
return btn;
|
||
}
|
||
|
||
/** @param {number} hz */
|
||
function banda(hz) {
|
||
return hz < 13 ? 'alpha' : 'beta';
|
||
}
|
||
|
||
/* ── Sesión ── */
|
||
|
||
async function abrirSesion(nombre) {
|
||
try {
|
||
const resp = await fetch(`/api/presets/${nombre}`);
|
||
if (!resp.ok) throw new Error(`API respondió ${resp.status}`);
|
||
sesionActual = await resp.json();
|
||
} catch (err) {
|
||
alert(`No pude abrir el preset: ${err.message}`);
|
||
return;
|
||
}
|
||
$('sesion-nombre').textContent = sesionActual.preset.name.replace('_', ' ');
|
||
$('sesion-desc').textContent = sesionActual.preset.description;
|
||
$('timer').textContent = formatear(sesionActual.schedule.duration_s);
|
||
$('beat-hz').textContent = `batido ${sesionActual.schedule.points[0].beat_hz} Hz`;
|
||
ocultarMensaje();
|
||
mostrarVista('sesion');
|
||
}
|
||
|
||
function mostrarVista(cual) {
|
||
$('vista-inicio').hidden = cual !== 'inicio';
|
||
$('vista-sesion').hidden = cual !== 'sesion';
|
||
$('vista-ajustes').hidden = cual !== 'ajustes';
|
||
$('nav-inicio').classList.toggle('activo', cual !== 'ajustes');
|
||
$('nav-ajustes').classList.toggle('activo', cual === 'ajustes');
|
||
}
|
||
|
||
async function alPlay() {
|
||
if (!sesionActual) return;
|
||
ocultarMensaje();
|
||
$('btn-play').disabled = true;
|
||
// El keep-alive debe arrancar de forma síncrona dentro del gesto,
|
||
// antes de cualquier await, para que iOS lo acepte como reproducción.
|
||
keepAliveIniciar();
|
||
vigilarKeepAlive();
|
||
try {
|
||
await motor.iniciar(sesionActual.schedule, {
|
||
volumenDb: Number($('volumen').value),
|
||
alTerminar: alTerminarSesion,
|
||
});
|
||
} catch (err) {
|
||
keepAliveParar();
|
||
mostrarMensaje(err.message);
|
||
$('btn-play').disabled = false;
|
||
return;
|
||
}
|
||
$('btn-play').hidden = true;
|
||
$('btn-play').disabled = false;
|
||
$('btn-pausa').hidden = false;
|
||
$('btn-stop').hidden = false;
|
||
mediaSessionConfigurar({
|
||
titulo: sesionActual.preset.name.replace('_', ' '),
|
||
manejadores: { play: reanudarTodo, pause: pausarTodo, stop: alStop },
|
||
});
|
||
mediaSessionEstado('playing');
|
||
temporizador.iniciar(() => ({
|
||
restante: sesionActual.schedule.duration_s - Math.max(motor.tiempoSesion, 0),
|
||
enPreroll: motor.tiempoSesion < 0,
|
||
batido: motor.batidoActual(),
|
||
}));
|
||
}
|
||
|
||
/** Evita reentradas cuando los eventos del <audio> reflejan nuestros propios cambios. */
|
||
let cambiandoPausa = false;
|
||
|
||
async function pausarTodo() {
|
||
if (!motor.activa || motor.pausada || cambiandoPausa) return;
|
||
cambiandoPausa = true;
|
||
try {
|
||
await motor.pausar();
|
||
keepAlivePausar();
|
||
} finally {
|
||
cambiandoPausa = false;
|
||
}
|
||
mediaSessionEstado('paused');
|
||
pintarPausa();
|
||
}
|
||
|
||
async function reanudarTodo() {
|
||
if (!motor.activa || !motor.pausada || cambiandoPausa) return;
|
||
cambiandoPausa = true;
|
||
try {
|
||
keepAliveIniciar();
|
||
await motor.reanudar();
|
||
} finally {
|
||
cambiandoPausa = false;
|
||
}
|
||
mediaSessionEstado('playing');
|
||
pintarPausa();
|
||
}
|
||
|
||
function alPausaClick() {
|
||
if (motor.pausada) reanudarTodo();
|
||
else pausarTodo();
|
||
}
|
||
|
||
function pintarPausa() {
|
||
$('btn-pausa').textContent = motor.pausada ? '▶\u00a0 Reanudar' : '⏸\u00a0 Pausar';
|
||
}
|
||
|
||
/**
|
||
* La detección de oído de los AirPods (o la pantalla de bloqueo) pausa el
|
||
* <audio> keep-alive: sincronizamos la sesión Web Audio con esos eventos
|
||
* para reanudar sin reiniciar.
|
||
*/
|
||
function vigilarKeepAlive() {
|
||
const el = keepAliveElemento();
|
||
if (!el || el.dataset.vigilado) return;
|
||
el.dataset.vigilado = '1';
|
||
el.addEventListener('pause', () => {
|
||
if (motor.activa && !motor.pausada && !cambiandoPausa) pausarTodo();
|
||
});
|
||
el.addEventListener('play', () => {
|
||
if (motor.activa && motor.pausada && !cambiandoPausa) reanudarTodo();
|
||
});
|
||
}
|
||
|
||
function alStop() {
|
||
motor.detener();
|
||
alTerminarSesion();
|
||
}
|
||
|
||
function alTerminarSesion() {
|
||
temporizador.parar();
|
||
keepAliveParar();
|
||
mediaSessionLimpiar();
|
||
$('btn-play').hidden = false;
|
||
$('btn-pausa').hidden = true;
|
||
$('btn-stop').hidden = true;
|
||
pintarPausa();
|
||
if (sesionActual) $('timer').textContent = formatear(sesionActual.schedule.duration_s);
|
||
const estado = $('beat-estado');
|
||
estado.hidden = true;
|
||
$('beat-hz').textContent = sesionActual
|
||
? `batido ${sesionActual.schedule.points[0].beat_hz} Hz`
|
||
: '—';
|
||
}
|
||
|
||
/** @param {{restante: number, enPreroll: boolean, batido: {hz: number, enRampa: boolean}}} d */
|
||
function pintarTic(d) {
|
||
$('timer').textContent = formatear(Math.max(d.restante, 0));
|
||
const estado = $('beat-estado');
|
||
if (motor.pausada) {
|
||
estado.textContent = 'en pausa';
|
||
estado.className = 'chip';
|
||
estado.hidden = false;
|
||
return;
|
||
}
|
||
if (d.enPreroll) {
|
||
$('beat-hz').textContent = 'preparando…';
|
||
estado.hidden = true;
|
||
return;
|
||
}
|
||
if (sesionActual) {
|
||
mediaSessionPosicion(
|
||
Math.max(motor.tiempoSesion, 0),
|
||
sesionActual.schedule.duration_s
|
||
);
|
||
}
|
||
$('beat-hz').textContent = `batido ${d.batido.hz.toFixed(1)} Hz`;
|
||
const clase = d.batido.enRampa ? 'transicion' : banda(d.batido.hz);
|
||
estado.textContent = clase === 'transicion' ? 'transición' : clase;
|
||
estado.className = `chip ${clase}`;
|
||
estado.hidden = false;
|
||
}
|
||
|
||
/** @param {number} segundos */
|
||
function formatear(segundos) {
|
||
const s = Math.round(segundos);
|
||
const mm = String(Math.floor(s / 60)).padStart(2, '0');
|
||
const ss = String(s % 60).padStart(2, '0');
|
||
return `${mm}:${ss}`;
|
||
}
|
||
|
||
function mostrarMensaje(texto) {
|
||
const m = $('mensaje');
|
||
m.textContent = texto;
|
||
m.hidden = false;
|
||
}
|
||
|
||
function ocultarMensaje() {
|
||
$('mensaje').hidden = true;
|
||
}
|
||
|
||
/* ── Ajustes AirPods ── */
|
||
|
||
const CLAVE_CHECKLIST = 'binaural-checklist';
|
||
const CLAVE_TEST = 'binaural-test-estereo';
|
||
|
||
function leerGuardado(clave, defecto) {
|
||
try {
|
||
const crudo = localStorage.getItem(clave);
|
||
return crudo ? JSON.parse(crudo) : defecto;
|
||
} catch {
|
||
return defecto;
|
||
}
|
||
}
|
||
|
||
function guardar(clave, valor) {
|
||
try {
|
||
localStorage.setItem(clave, JSON.stringify(valor));
|
||
} catch {
|
||
/* modo privado sin almacenamiento: la marca no persiste */
|
||
}
|
||
}
|
||
|
||
function pintarChecklist() {
|
||
const marcados = leerGuardado(CLAVE_CHECKLIST, {});
|
||
const lista = $('lista-checklist');
|
||
lista.replaceChildren(
|
||
...CHECKLIST.map((item) => {
|
||
const li = document.createElement('li');
|
||
const caja = document.createElement('input');
|
||
caja.type = 'checkbox';
|
||
caja.id = `chk-${item.id}`;
|
||
caja.checked = Boolean(marcados[item.id]);
|
||
caja.addEventListener('change', () => {
|
||
const estado = leerGuardado(CLAVE_CHECKLIST, {});
|
||
estado[item.id] = caja.checked;
|
||
guardar(CLAVE_CHECKLIST, estado);
|
||
});
|
||
const etiqueta = document.createElement('label');
|
||
etiqueta.htmlFor = caja.id;
|
||
etiqueta.className = 'texto';
|
||
etiqueta.innerHTML = `${item.texto}<span class="ruta">${item.ruta}</span>`;
|
||
li.append(caja, etiqueta);
|
||
return li;
|
||
})
|
||
);
|
||
const testOk = $('test-ok');
|
||
testOk.checked = Boolean(leerGuardado(CLAVE_TEST, false));
|
||
testOk.addEventListener('change', () => guardar(CLAVE_TEST, testOk.checked));
|
||
}
|
||
|
||
/** @param {'izquierda'|'derecha'|'binaural'} canal @param {HTMLButtonElement} boton */
|
||
async function probarTono(canal, boton) {
|
||
if (motor.activa) return; // no mezclar con una sesión en curso
|
||
const botones = [$('test-izq'), $('test-der'), $('test-bin')];
|
||
botones.forEach((b) => (b.disabled = true));
|
||
boton.classList.add('sonando');
|
||
try {
|
||
await motor.tonoDePrueba(canal, { dur: canal === 'binaural' ? 5 : 3 });
|
||
} catch (err) {
|
||
mostrarMensaje(err.message);
|
||
} finally {
|
||
boton.classList.remove('sonando');
|
||
botones.forEach((b) => (b.disabled = false));
|
||
}
|
||
}
|
||
|
||
/* ── Cableado ── */
|
||
|
||
$('btn-play').addEventListener('click', alPlay);
|
||
$('btn-pausa').addEventListener('click', alPausaClick);
|
||
$('btn-stop').addEventListener('click', alStop);
|
||
$('nav-inicio').addEventListener('click', () => mostrarVista(motor.activa ? 'sesion' : 'inicio'));
|
||
$('nav-ajustes').addEventListener('click', () => mostrarVista('ajustes'));
|
||
$('test-izq').addEventListener('click', (e) => probarTono('izquierda', e.currentTarget));
|
||
$('test-der').addEventListener('click', (e) => probarTono('derecha', e.currentTarget));
|
||
$('test-bin').addEventListener('click', (e) => probarTono('binaural', e.currentTarget));
|
||
|
||
// Interrupciones de iOS (llamada, Siri, detección de oído): reflejar en la UI.
|
||
motor.alEstado = () => {
|
||
if (motor.activa) {
|
||
mediaSessionEstado(motor.pausada ? 'paused' : 'playing');
|
||
pintarPausa();
|
||
}
|
||
};
|
||
|
||
pintarChecklist();
|
||
$('btn-volver').addEventListener('click', () => {
|
||
if (motor.activa) alStop();
|
||
mostrarVista('inicio');
|
||
});
|
||
$('volumen').addEventListener('input', (e) => motor.cambiarVolumen(Number(e.target.value)));
|
||
|
||
cargarPresets();
|
||
|
||
// Gancho de depuración y pruebas (Playwright).
|
||
window.__binaural = { motor };
|