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)
This commit is contained in:
1 parent
d0d7683c29
commit
1a6977a59e
7 files changed
+623
No files matched your search
@@ -0,0 +1,79 @@
|
|||||||
|
# Pruebas en dispositivo real · iPhone + AirPods Pro 3
|
||||||
|
|
||||||
|
Guion del **criterio de aceptación 11**. Se corre desde la URL pública
|
||||||
|
(`https://binaurals.collinasystems.com.mx`) en Safari de iOS, con los
|
||||||
|
AirPods Pro 3 conectados. Rellena la columna **Resultado** de cada paso
|
||||||
|
(✅ / ❌ + nota) y la sección final.
|
||||||
|
|
||||||
|
> Antes de empezar: iPhone con volumen al 30–50 %, AirPods con batería,
|
||||||
|
> sin música ni podcasts sonando en otra app.
|
||||||
|
|
||||||
|
## A · Preparación (una sola vez)
|
||||||
|
|
||||||
|
1. Abre `https://binaurals.collinasystems.com.mx` en Safari.
|
||||||
|
2. Ve a **Ajustes 🎧** (barra inferior) y recorre el **checklist completo**,
|
||||||
|
marcando cada punto tras aplicarlo en iOS. Los dos críticos: **Audio
|
||||||
|
mono desactivado** y **Audio Espacial desactivado**.
|
||||||
|
3. Compartir → **Añadir a pantalla de inicio** (opcional, para lanzarla
|
||||||
|
como app).
|
||||||
|
|
||||||
|
## B · Test de separación estéreo
|
||||||
|
|
||||||
|
4. En **Ajustes 🎧**, toca **◐ Solo izquierdo**: debe sonar SOLO en el
|
||||||
|
oído izquierdo. → Resultado:
|
||||||
|
5. Toca **◑ Solo derecho**: SOLO en el derecho. → Resultado:
|
||||||
|
6. Toca **◉ Batido binaural**: suena en ambos oídos y se percibe una
|
||||||
|
pulsación suave (~10 por segundo) "dentro" de la cabeza. → Resultado:
|
||||||
|
7. Marca la casilla de confirmación. Si L/R salen invertidos o algún lado
|
||||||
|
suena en ambos oídos, NO sigas: revisa audio mono/balance y repite.
|
||||||
|
|
||||||
|
## C · Arranque y pre-roll
|
||||||
|
|
||||||
|
8. Ve a **Presets** y abre **relajacion**. Toca **▶ Iniciar**.
|
||||||
|
9. Comprueba: hay ~1.5 s de silencio y el tono entra con un fade suave
|
||||||
|
**desde el principio, sin cortarse el inicio** (el enlace Bluetooth
|
||||||
|
tarda en arrancar; el pre-roll debe absorberlo). → Resultado:
|
||||||
|
10. El timer no arranca de golpe adelantado: empieza a contar
|
||||||
|
aproximadamente cuando empiezas a oír el tono. → Resultado:
|
||||||
|
|
||||||
|
## D · Pantalla bloqueada (≥ 5 min)
|
||||||
|
|
||||||
|
11. Con la sesión sonando, **bloquea el iPhone** (botón lateral).
|
||||||
|
12. Espera **5 minutos** sin tocar nada. El audio debe seguir sonando
|
||||||
|
todo el tiempo, sin cortes ni silencios. → Resultado:
|
||||||
|
13. Enciende la pantalla sin desbloquear: en la **pantalla de bloqueo**
|
||||||
|
debe verse la sesión (título del preset) con controles de
|
||||||
|
reproducción. → Resultado:
|
||||||
|
14. Desbloquea y vuelve a Safari: el timer debe ir ~5 min más abajo,
|
||||||
|
coherente con el tiempo transcurrido (no reiniciado). → Resultado:
|
||||||
|
|
||||||
|
## E · Controles del AirPod (tallo)
|
||||||
|
|
||||||
|
15. Con la sesión sonando, **presiona el tallo** una vez: el audio se
|
||||||
|
pausa. → Resultado:
|
||||||
|
16. La UI (si la pantalla está encendida) muestra "en pausa" y el timer
|
||||||
|
congelado. → Resultado:
|
||||||
|
17. Presiona el tallo de nuevo: el audio **reanuda donde iba**, sin
|
||||||
|
reiniciar la sesión ni el timer. → Resultado:
|
||||||
|
|
||||||
|
## F · Detección de oído e interrupciones
|
||||||
|
|
||||||
|
18. Sácate un AirPod: el audio debe pausarse solo. Vuelve a ponértelo y
|
||||||
|
reanuda (con el tallo o desde la pantalla de bloqueo): la sesión
|
||||||
|
continúa donde iba. → Resultado:
|
||||||
|
19. Deja que la sesión de **descanso** (15 min) llegue al final: el
|
||||||
|
fade-out termina limpio y la UI vuelve al estado inicial. → Resultado:
|
||||||
|
*(opcional si el tiempo aprieta)*
|
||||||
|
|
||||||
|
## Registro de resultados
|
||||||
|
|
||||||
|
| Fecha | iOS | Versión app (tag/commit) | Pasos ❌ | Notas |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| | | | | |
|
||||||
|
|
||||||
|
### Si falla la sección D (bloqueo de pantalla)
|
||||||
|
|
||||||
|
Es el riesgo conocido de Web Audio en iOS. Documenta aquí exactamente qué
|
||||||
|
pasó (¿se cortó al bloquear? ¿a los N segundos? ¿reanudó al desbloquear?)
|
||||||
|
y avisa: el plan B acordado es evaluar **streaming desde el servidor**
|
||||||
|
(`<audio>` sobre `/api/export`) antes de continuar con la fase 5.
|
||||||
+182
@@ -0,0 +1,182 @@
|
|||||||
|
/**
|
||||||
|
* Optimización iOS + AirPods Pro:
|
||||||
|
* — checklist de configuración con rutas de iOS,
|
||||||
|
* — Media Session (pantalla de bloqueo + controles del tallo),
|
||||||
|
* — keep-alive con <audio> silencioso en loop para que iOS trate la
|
||||||
|
* página como reproducción de medios y no suspenda el audio al
|
||||||
|
* bloquear la pantalla.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** @type {{id: string, texto: string, ruta: string}[]} */
|
||||||
|
export const CHECKLIST = [
|
||||||
|
{
|
||||||
|
id: 'espacial',
|
||||||
|
texto: 'Audio Espacial / Spatialize Stereo → Desactivado',
|
||||||
|
ruta: 'Centro de Control → mantén pulsado el control de volumen → Audio Espacial',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'anc',
|
||||||
|
texto: 'Control de ruido → Cancelación activa (fija)',
|
||||||
|
ruta: 'Centro de Control → mantén pulsado el volumen → Control de ruido',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'adaptativo',
|
||||||
|
texto: 'Audio Adaptativo → Desactivado',
|
||||||
|
ruta: 'Centro de Control → Control de ruido (elige Cancelación, no Adaptativo)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'conversacion',
|
||||||
|
texto: 'Conciencia de Conversación → Desactivada',
|
||||||
|
ruta: 'Ajustes → [tus AirPods] → Conciencia de Conversación',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'volumen-personalizado',
|
||||||
|
texto: 'Volumen Personalizado → Desactivado',
|
||||||
|
ruta: 'Ajustes → [tus AirPods] → Ajustes de audio',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mono',
|
||||||
|
texto: 'Audio mono → DESACTIVADO (activado mata el efecto binaural)',
|
||||||
|
ruta: 'Ajustes → Accesibilidad → Audio y visual → Audio mono',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'balance',
|
||||||
|
texto: 'Balance L/R centrado',
|
||||||
|
ruta: 'Ajustes → Accesibilidad → Audio y visual → Balance',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'adaptaciones',
|
||||||
|
texto: 'Adaptaciones de auriculares y función Audífono → Desactivadas',
|
||||||
|
ruta: 'Ajustes → Accesibilidad → Audio y visual → Adaptaciones de auriculares',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sello',
|
||||||
|
texto: 'Prueba de ajuste de almohadillas superada (sello correcto)',
|
||||||
|
ruta: 'Ajustes → [tus AirPods] → Prueba de ajuste de las almohadillas',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/* ── Keep-alive: <audio> silencioso en loop ── */
|
||||||
|
|
||||||
|
/** @type {HTMLAudioElement|null} */
|
||||||
|
let elementoKA = null;
|
||||||
|
|
||||||
|
/** WAV de 1 s de silencio (mono, 8 kHz, 16-bit) generado en memoria. */
|
||||||
|
function urlWavSilencioso() {
|
||||||
|
const sr = 8000;
|
||||||
|
const n = sr; // 1 segundo
|
||||||
|
const buf = new ArrayBuffer(44 + n * 2);
|
||||||
|
const v = new DataView(buf);
|
||||||
|
const escribir = (pos, texto) => {
|
||||||
|
for (let i = 0; i < texto.length; i++) v.setUint8(pos + i, texto.charCodeAt(i));
|
||||||
|
};
|
||||||
|
escribir(0, 'RIFF');
|
||||||
|
v.setUint32(4, 36 + n * 2, true);
|
||||||
|
escribir(8, 'WAVE');
|
||||||
|
escribir(12, 'fmt ');
|
||||||
|
v.setUint32(16, 16, true);
|
||||||
|
v.setUint16(20, 1, true); // PCM
|
||||||
|
v.setUint16(22, 1, true); // mono
|
||||||
|
v.setUint32(24, sr, true);
|
||||||
|
v.setUint32(28, sr * 2, true);
|
||||||
|
v.setUint16(32, 2, true);
|
||||||
|
v.setUint16(34, 16, true);
|
||||||
|
escribir(36, 'data');
|
||||||
|
v.setUint32(40, n * 2, true);
|
||||||
|
return URL.createObjectURL(new Blob([buf], { type: 'audio/wav' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Elemento keep-alive actual (o null si nunca se creó). */
|
||||||
|
export function keepAliveElemento() {
|
||||||
|
return elementoKA;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arranca (o reanuda) el loop silencioso. Llamar SIN await y dentro del
|
||||||
|
* gesto del usuario, antes de cualquier operación asíncrona.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export function keepAliveIniciar() {
|
||||||
|
if (!elementoKA) {
|
||||||
|
elementoKA = new Audio(urlWavSilencioso());
|
||||||
|
elementoKA.loop = true;
|
||||||
|
elementoKA.setAttribute('playsinline', '');
|
||||||
|
}
|
||||||
|
return elementoKA.play().catch(() => {
|
||||||
|
/* si iOS lo rechaza, la sesión Web Audio sigue intentándolo sola */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function keepAlivePausar() {
|
||||||
|
if (elementoKA) elementoKA.pause();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function keepAliveParar() {
|
||||||
|
if (elementoKA) {
|
||||||
|
elementoKA.pause();
|
||||||
|
elementoKA.currentTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Media Session: pantalla de bloqueo y controles del tallo ── */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{titulo: string, artista?: string,
|
||||||
|
* manejadores: Object<string, (() => void)|null>}} datos
|
||||||
|
* @returns {boolean} true si el navegador soporta Media Session
|
||||||
|
*/
|
||||||
|
export function mediaSessionConfigurar({ titulo, artista = 'Binaurales · Collina', manejadores }) {
|
||||||
|
if (!('mediaSession' in navigator)) return false;
|
||||||
|
navigator.mediaSession.metadata = new MediaMetadata({
|
||||||
|
title: titulo,
|
||||||
|
artist: artista,
|
||||||
|
artwork: [
|
||||||
|
{ src: '/icons/icono-192.png', sizes: '192x192', type: 'image/png' },
|
||||||
|
{ src: '/icons/icono-512.png', sizes: '512x512', type: 'image/png' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
for (const [accion, fn] of Object.entries(manejadores)) {
|
||||||
|
try {
|
||||||
|
navigator.mediaSession.setActionHandler(accion, fn);
|
||||||
|
} catch {
|
||||||
|
/* acción no soportada en este navegador */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {'playing'|'paused'|'none'} estado */
|
||||||
|
export function mediaSessionEstado(estado) {
|
||||||
|
if ('mediaSession' in navigator) navigator.mediaSession.playbackState = estado;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Actualiza la barra de progreso de la pantalla de bloqueo.
|
||||||
|
* @param {number} posicion — segundos transcurridos de sesión
|
||||||
|
* @param {number} duracion — segundos totales
|
||||||
|
*/
|
||||||
|
export function mediaSessionPosicion(posicion, duracion) {
|
||||||
|
if (!('mediaSession' in navigator) || !navigator.mediaSession.setPositionState) return;
|
||||||
|
try {
|
||||||
|
navigator.mediaSession.setPositionState({
|
||||||
|
duration: duracion,
|
||||||
|
position: Math.min(Math.max(posicion, 0), duracion),
|
||||||
|
playbackRate: 1,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* valores fuera de rango en algún borde: ignorar */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mediaSessionLimpiar() {
|
||||||
|
if (!('mediaSession' in navigator)) return;
|
||||||
|
mediaSessionEstado('none');
|
||||||
|
navigator.mediaSession.metadata = null;
|
||||||
|
for (const accion of ['play', 'pause', 'stop']) {
|
||||||
|
try {
|
||||||
|
navigator.mediaSession.setActionHandler(accion, null);
|
||||||
|
} catch {
|
||||||
|
/* nada */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+178
@@ -1,5 +1,16 @@
|
|||||||
/** Navegación, estado y pegamento entre la API y el motor de audio. */
|
/** 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 { MotorBinaural } from './audio-engine.js';
|
||||||
import { Temporizador } from './timer.js';
|
import { Temporizador } from './timer.js';
|
||||||
|
|
||||||
@@ -76,25 +87,39 @@ async function abrirSesion(nombre) {
|
|||||||
function mostrarVista(cual) {
|
function mostrarVista(cual) {
|
||||||
$('vista-inicio').hidden = cual !== 'inicio';
|
$('vista-inicio').hidden = cual !== 'inicio';
|
||||||
$('vista-sesion').hidden = cual !== 'sesion';
|
$('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() {
|
async function alPlay() {
|
||||||
if (!sesionActual) return;
|
if (!sesionActual) return;
|
||||||
ocultarMensaje();
|
ocultarMensaje();
|
||||||
$('btn-play').disabled = true;
|
$('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 {
|
try {
|
||||||
await motor.iniciar(sesionActual.schedule, {
|
await motor.iniciar(sesionActual.schedule, {
|
||||||
volumenDb: Number($('volumen').value),
|
volumenDb: Number($('volumen').value),
|
||||||
alTerminar: alTerminarSesion,
|
alTerminar: alTerminarSesion,
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
keepAliveParar();
|
||||||
mostrarMensaje(err.message);
|
mostrarMensaje(err.message);
|
||||||
$('btn-play').disabled = false;
|
$('btn-play').disabled = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$('btn-play').hidden = true;
|
$('btn-play').hidden = true;
|
||||||
$('btn-play').disabled = false;
|
$('btn-play').disabled = false;
|
||||||
|
$('btn-pausa').hidden = false;
|
||||||
$('btn-stop').hidden = false;
|
$('btn-stop').hidden = false;
|
||||||
|
mediaSessionConfigurar({
|
||||||
|
titulo: sesionActual.preset.name.replace('_', ' '),
|
||||||
|
manejadores: { play: reanudarTodo, pause: pausarTodo, stop: alStop },
|
||||||
|
});
|
||||||
|
mediaSessionEstado('playing');
|
||||||
temporizador.iniciar(() => ({
|
temporizador.iniciar(() => ({
|
||||||
restante: sesionActual.schedule.duration_s - Math.max(motor.tiempoSesion, 0),
|
restante: sesionActual.schedule.duration_s - Math.max(motor.tiempoSesion, 0),
|
||||||
enPreroll: motor.tiempoSesion < 0,
|
enPreroll: motor.tiempoSesion < 0,
|
||||||
@@ -102,6 +127,61 @@ async function alPlay() {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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() {
|
function alStop() {
|
||||||
motor.detener();
|
motor.detener();
|
||||||
alTerminarSesion();
|
alTerminarSesion();
|
||||||
@@ -109,8 +189,12 @@ function alStop() {
|
|||||||
|
|
||||||
function alTerminarSesion() {
|
function alTerminarSesion() {
|
||||||
temporizador.parar();
|
temporizador.parar();
|
||||||
|
keepAliveParar();
|
||||||
|
mediaSessionLimpiar();
|
||||||
$('btn-play').hidden = false;
|
$('btn-play').hidden = false;
|
||||||
|
$('btn-pausa').hidden = true;
|
||||||
$('btn-stop').hidden = true;
|
$('btn-stop').hidden = true;
|
||||||
|
pintarPausa();
|
||||||
if (sesionActual) $('timer').textContent = formatear(sesionActual.schedule.duration_s);
|
if (sesionActual) $('timer').textContent = formatear(sesionActual.schedule.duration_s);
|
||||||
const estado = $('beat-estado');
|
const estado = $('beat-estado');
|
||||||
estado.hidden = true;
|
estado.hidden = true;
|
||||||
@@ -123,11 +207,23 @@ function alTerminarSesion() {
|
|||||||
function pintarTic(d) {
|
function pintarTic(d) {
|
||||||
$('timer').textContent = formatear(Math.max(d.restante, 0));
|
$('timer').textContent = formatear(Math.max(d.restante, 0));
|
||||||
const estado = $('beat-estado');
|
const estado = $('beat-estado');
|
||||||
|
if (motor.pausada) {
|
||||||
|
estado.textContent = 'en pausa';
|
||||||
|
estado.className = 'chip';
|
||||||
|
estado.hidden = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (d.enPreroll) {
|
if (d.enPreroll) {
|
||||||
$('beat-hz').textContent = 'preparando…';
|
$('beat-hz').textContent = 'preparando…';
|
||||||
estado.hidden = true;
|
estado.hidden = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (sesionActual) {
|
||||||
|
mediaSessionPosicion(
|
||||||
|
Math.max(motor.tiempoSesion, 0),
|
||||||
|
sesionActual.schedule.duration_s
|
||||||
|
);
|
||||||
|
}
|
||||||
$('beat-hz').textContent = `batido ${d.batido.hz.toFixed(1)} Hz`;
|
$('beat-hz').textContent = `batido ${d.batido.hz.toFixed(1)} Hz`;
|
||||||
const clase = d.batido.enRampa ? 'transicion' : banda(d.batido.hz);
|
const clase = d.batido.enRampa ? 'transicion' : banda(d.batido.hz);
|
||||||
estado.textContent = clase === 'transicion' ? 'transición' : clase;
|
estado.textContent = clase === 'transicion' ? 'transición' : clase;
|
||||||
@@ -153,10 +249,92 @@ function ocultarMensaje() {
|
|||||||
$('mensaje').hidden = true;
|
$('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 ── */
|
/* ── Cableado ── */
|
||||||
|
|
||||||
$('btn-play').addEventListener('click', alPlay);
|
$('btn-play').addEventListener('click', alPlay);
|
||||||
|
$('btn-pausa').addEventListener('click', alPausaClick);
|
||||||
$('btn-stop').addEventListener('click', alStop);
|
$('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', () => {
|
$('btn-volver').addEventListener('click', () => {
|
||||||
if (motor.activa) alStop();
|
if (motor.activa) alStop();
|
||||||
mostrarVista('inicio');
|
mostrarVista('inicio');
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ export class MotorBinaural {
|
|||||||
this.tFin = 0;
|
this.tFin = 0;
|
||||||
/** @type {Map<string, AudioBuffer>} */
|
/** @type {Map<string, AudioBuffer>} */
|
||||||
this._ruidos = new Map();
|
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. */
|
/** Crea/reanuda el AudioContext. Debe llamarse dentro del gesto del usuario. */
|
||||||
@@ -50,6 +52,9 @@ export class MotorBinaural {
|
|||||||
const Ctor = window.AudioContext || window.webkitAudioContext;
|
const Ctor = window.AudioContext || window.webkitAudioContext;
|
||||||
this.ctx = new Ctor(); // sin forzar sampleRate: usar el nativo
|
this.ctx = new Ctor(); // sin forzar sampleRate: usar el nativo
|
||||||
if (navigator.audioSession) navigator.audioSession.type = 'playback';
|
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 === 'suspended') await this.ctx.resume();
|
||||||
if (this.ctx.state !== 'running') {
|
if (this.ctx.state !== 'running') {
|
||||||
@@ -198,11 +203,67 @@ export class MotorBinaural {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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). */
|
/** true mientras hay sesión sonando (o en pre-roll). */
|
||||||
get activa() {
|
get activa() {
|
||||||
return this.nodos !== null;
|
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):
|
* 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.
|
* reloj de audio menos la latencia de salida, no el reloj del sistema.
|
||||||
|
|||||||
@@ -33,6 +33,7 @@
|
|||||||
|
|
||||||
<div class="controles">
|
<div class="controles">
|
||||||
<button id="btn-play" class="btn-grande btn-play" type="button">▶ Iniciar</button>
|
<button id="btn-play" class="btn-grande btn-play" type="button">▶ Iniciar</button>
|
||||||
|
<button id="btn-pausa" class="btn-grande btn-pausa" type="button" hidden>⏸ Pausar</button>
|
||||||
<button id="btn-stop" class="btn-grande btn-stop" type="button" hidden>■ Detener</button>
|
<button id="btn-stop" class="btn-grande btn-stop" type="button" hidden>■ Detener</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -44,6 +45,44 @@
|
|||||||
<p id="mensaje" class="mensaje" role="alert" hidden></p>
|
<p id="mensaje" class="mensaje" role="alert" hidden></p>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<main id="vista-ajustes" class="vista" hidden>
|
||||||
|
<h2>Ajustes AirPods</h2>
|
||||||
|
<p class="desc">
|
||||||
|
Los AirPods Pro van por Bluetooth con códec AAC, que preserva bien los
|
||||||
|
tonos puros. Lo que sí puede romper el efecto binaural es el
|
||||||
|
procesamiento de iOS: desactiva todo lo de esta lista antes de tu
|
||||||
|
primera sesión.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section class="bloque">
|
||||||
|
<h3>Test de separación estéreo</h3>
|
||||||
|
<p class="desc">
|
||||||
|
Con los audífonos bien puestos, toca cada botón y confirma: el
|
||||||
|
primero suena SOLO en el oído izquierdo, el segundo SOLO en el
|
||||||
|
derecho, y el batido se percibe con los dos (una pulsación suave).
|
||||||
|
</p>
|
||||||
|
<div class="controles-test">
|
||||||
|
<button id="test-izq" class="btn-test" type="button">◐ Solo izquierdo</button>
|
||||||
|
<button id="test-der" class="btn-test" type="button">◑ Solo derecho</button>
|
||||||
|
<button id="test-bin" class="btn-test" type="button">◉ Batido binaural</button>
|
||||||
|
</div>
|
||||||
|
<label class="confirmacion">
|
||||||
|
<input type="checkbox" id="test-ok">
|
||||||
|
<span>Escuché cada tono en el oído correcto y el batido con ambos</span>
|
||||||
|
</label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="bloque">
|
||||||
|
<h3>Checklist de configuración</h3>
|
||||||
|
<ul id="lista-checklist" class="checklist"></ul>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<nav class="nav">
|
||||||
|
<button id="nav-inicio" class="nav-btn activo" type="button">Presets</button>
|
||||||
|
<button id="nav-ajustes" class="nav-btn" type="button">Ajustes 🎧</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
<script type="module" src="app.js"></script>
|
<script type="module" src="app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -103,6 +103,7 @@ body {
|
|||||||
}
|
}
|
||||||
.btn-play { background: var(--acento); color: #04160f; }
|
.btn-play { background: var(--acento); color: #04160f; }
|
||||||
.btn-stop { background: var(--peligro); color: #fff; }
|
.btn-stop { background: var(--peligro); color: #fff; }
|
||||||
|
.btn-pausa { background: var(--panel); color: var(--texto); border: 1px solid var(--borde); }
|
||||||
.btn-grande:disabled { opacity: 0.5; }
|
.btn-grande:disabled { opacity: 0.5; }
|
||||||
|
|
||||||
.volumen { display: block; margin-top: 1.6rem; color: var(--texto-suave); font-size: 0.9rem; }
|
.volumen { display: block; margin-top: 1.6rem; color: var(--texto-suave); font-size: 0.9rem; }
|
||||||
@@ -115,3 +116,44 @@ body {
|
|||||||
background: color-mix(in srgb, var(--peligro) 15%, transparent);
|
background: color-mix(in srgb, var(--peligro) 15%, transparent);
|
||||||
color: var(--peligro); font-size: 0.92rem;
|
color: var(--peligro); font-size: 0.92rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Navegación inferior ── */
|
||||||
|
.nav {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 0; left: 0; right: 0;
|
||||||
|
display: flex;
|
||||||
|
background: color-mix(in srgb, var(--fondo) 88%, transparent);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
border-top: 1px solid var(--borde);
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
}
|
||||||
|
.nav-btn {
|
||||||
|
flex: 1; padding: 0.9rem; background: none; border: none;
|
||||||
|
color: var(--texto-suave); font-size: 1rem; cursor: pointer;
|
||||||
|
}
|
||||||
|
.nav-btn.activo { color: var(--acento); font-weight: 600; }
|
||||||
|
.vista { padding-bottom: 5rem; }
|
||||||
|
|
||||||
|
/* ── Ajustes AirPods ── */
|
||||||
|
.bloque {
|
||||||
|
background: var(--panel); border: 1px solid var(--borde);
|
||||||
|
border-radius: 14px; padding: 1rem 1.1rem; margin-top: 1rem;
|
||||||
|
}
|
||||||
|
.bloque h3 { margin: 0 0 0.4rem; font-size: 1.05rem; }
|
||||||
|
.controles-test { display: grid; gap: 0.6rem; margin: 0.8rem 0; }
|
||||||
|
.btn-test {
|
||||||
|
padding: 0.9rem; border-radius: 12px; border: 1px solid var(--borde);
|
||||||
|
background: var(--fondo); color: var(--texto); font-size: 1.05rem; cursor: pointer;
|
||||||
|
}
|
||||||
|
.btn-test:disabled { opacity: 0.5; }
|
||||||
|
.btn-test.sonando { border-color: var(--acento); color: var(--acento); }
|
||||||
|
.confirmacion {
|
||||||
|
display: flex; gap: 0.6rem; align-items: flex-start;
|
||||||
|
font-size: 0.92rem; color: var(--texto-suave);
|
||||||
|
}
|
||||||
|
.confirmacion input { width: 1.2rem; height: 1.2rem; accent-color: var(--acento); }
|
||||||
|
.checklist { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.7rem; }
|
||||||
|
.checklist li { display: flex; gap: 0.6rem; align-items: flex-start; }
|
||||||
|
.checklist input { width: 1.2rem; height: 1.2rem; flex-shrink: 0; accent-color: var(--acento); }
|
||||||
|
.checklist .texto { font-size: 0.95rem; }
|
||||||
|
.checklist .ruta { display: block; color: var(--texto-suave); font-size: 0.8rem; margin-top: 0.15rem; }
|
||||||
@@ -25,3 +25,45 @@ test('lista presets, reproduce y el timer avanza', async ({ page }) => {
|
|||||||
await page.click('#btn-stop');
|
await page.click('#btn-stop');
|
||||||
await expect(page.locator('#btn-play')).toBeVisible();
|
await expect(page.locator('#btn-play')).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('pausa congela el timer y reanudar continúa sin reiniciar', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.locator('.tarjeta').filter({ hasText: 'relajacion' }).click();
|
||||||
|
await page.click('#btn-play');
|
||||||
|
await expect(page.locator('#timer')).not.toHaveText('20:00', { timeout: 10_000 });
|
||||||
|
|
||||||
|
await page.click('#btn-pausa');
|
||||||
|
await expect
|
||||||
|
.poll(() => page.evaluate(() => window.__binaural.motor.ctx.state))
|
||||||
|
.toBe('suspended');
|
||||||
|
const congelado = await page.locator('#timer').innerText();
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
await expect(page.locator('#timer')).toHaveText(congelado);
|
||||||
|
await expect(page.locator('#beat-estado')).toHaveText('en pausa');
|
||||||
|
|
||||||
|
await page.click('#btn-pausa'); // reanudar
|
||||||
|
await expect
|
||||||
|
.poll(() => page.evaluate(() => window.__binaural.motor.ctx.state))
|
||||||
|
.toBe('running');
|
||||||
|
await page.waitForTimeout(1600);
|
||||||
|
await expect(page.locator('#timer')).not.toHaveText(congelado);
|
||||||
|
await page.click('#btn-stop');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('vista de ajustes: checklist y test estéreo', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await page.click('#nav-ajustes');
|
||||||
|
await expect(page.locator('#vista-ajustes')).toBeVisible();
|
||||||
|
await expect(page.locator('#lista-checklist li')).toHaveCount(9);
|
||||||
|
|
||||||
|
// Una marca del checklist persiste en localStorage tras recargar.
|
||||||
|
await page.check('#chk-mono');
|
||||||
|
await page.reload();
|
||||||
|
await page.click('#nav-ajustes');
|
||||||
|
await expect(page.locator('#chk-mono')).toBeChecked();
|
||||||
|
|
||||||
|
// El tono de prueba corre y termina reactivando los botones.
|
||||||
|
await page.click('#test-izq');
|
||||||
|
await expect(page.locator('#test-der')).toBeDisabled();
|
||||||
|
await expect(page.locator('#test-der')).toBeEnabled({ timeout: 10_000 });
|
||||||
|
});
|
||||||
Reference in new issue
Block a user