feat(web): frontend base — motor Web Audio, sesión con timer y presets
- 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
This commit is contained in:
1 parent
6d006af4f9
commit
d0d7683c29
9 files changed
+733
-2
No files matched your search
Generated
+76
@@ -0,0 +1,76 @@
|
|||||||
|
{
|
||||||
|
"name": "collina-binaurals-web",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "collina-binaurals-web",
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.49.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.62.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz",
|
||||||
|
"integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.62.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.62.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
|
||||||
|
"integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.62.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.62.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
|
||||||
|
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "collina-binaurals-web",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"test": "playwright test"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.49.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// Prueba de humo del frontend (criterio 10): Chromium contra la app real.
|
||||||
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: 'web/tests',
|
||||||
|
timeout: 30_000,
|
||||||
|
use: { baseURL: 'http://127.0.0.1:8123' },
|
||||||
|
webServer: {
|
||||||
|
command: 'uv run uvicorn binaural.api:app --host 127.0.0.1 --port 8123',
|
||||||
|
cwd: 'backend',
|
||||||
|
url: 'http://127.0.0.1:8123/api/health',
|
||||||
|
reuseExistingServer: true,
|
||||||
|
timeout: 30_000,
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: 'chromium',
|
||||||
|
use: {
|
||||||
|
browserName: 'chromium',
|
||||||
|
launchOptions: { args: ['--autoplay-policy=no-user-gesture-required'] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
+169
@@ -0,0 +1,169 @@
|
|||||||
|
/** Navegación, estado y pegamento entre la API y el motor de audio. */
|
||||||
|
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function alPlay() {
|
||||||
|
if (!sesionActual) return;
|
||||||
|
ocultarMensaje();
|
||||||
|
$('btn-play').disabled = true;
|
||||||
|
try {
|
||||||
|
await motor.iniciar(sesionActual.schedule, {
|
||||||
|
volumenDb: Number($('volumen').value),
|
||||||
|
alTerminar: alTerminarSesion,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
mostrarMensaje(err.message);
|
||||||
|
$('btn-play').disabled = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$('btn-play').hidden = true;
|
||||||
|
$('btn-play').disabled = false;
|
||||||
|
$('btn-stop').hidden = false;
|
||||||
|
temporizador.iniciar(() => ({
|
||||||
|
restante: sesionActual.schedule.duration_s - Math.max(motor.tiempoSesion, 0),
|
||||||
|
enPreroll: motor.tiempoSesion < 0,
|
||||||
|
batido: motor.batidoActual(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function alStop() {
|
||||||
|
motor.detener();
|
||||||
|
alTerminarSesion();
|
||||||
|
}
|
||||||
|
|
||||||
|
function alTerminarSesion() {
|
||||||
|
temporizador.parar();
|
||||||
|
$('btn-play').hidden = false;
|
||||||
|
$('btn-stop').hidden = true;
|
||||||
|
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 (d.enPreroll) {
|
||||||
|
$('beat-hz').textContent = 'preparando…';
|
||||||
|
estado.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$('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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Cableado ── */
|
||||||
|
|
||||||
|
$('btn-play').addEventListener('click', alPlay);
|
||||||
|
$('btn-stop').addEventListener('click', alStop);
|
||||||
|
$('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 };
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
/**
|
||||||
|
* 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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
-2
@@ -1,5 +1,49 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="es">
|
<html lang="es">
|
||||||
<head><meta charset="utf-8"><title>collina-binaurals</title></head>
|
<head>
|
||||||
<body><p>Frontend en construcción (fase 3).</p></body>
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="theme-color" content="#0d1117">
|
||||||
|
<title>Binaurales · Collina</title>
|
||||||
|
<link rel="stylesheet" href="styles.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="cabecera">
|
||||||
|
<h1>Binaurales</h1>
|
||||||
|
<p class="aviso">🎧 Usa audífonos · volumen moderado · no lo uses al conducir</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="vista-inicio" class="vista">
|
||||||
|
<section id="lista-presets" class="tarjetas" aria-live="polite">
|
||||||
|
<p class="cargando">Cargando presets…</p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<main id="vista-sesion" class="vista" hidden>
|
||||||
|
<button id="btn-volver" class="btn-volver" type="button">‹ Presets</button>
|
||||||
|
<h2 id="sesion-nombre"></h2>
|
||||||
|
<p id="sesion-desc" class="desc"></p>
|
||||||
|
|
||||||
|
<div id="timer" class="timer" aria-live="off">--:--</div>
|
||||||
|
|
||||||
|
<div class="indicador">
|
||||||
|
<span id="beat-hz" class="beat-hz">—</span>
|
||||||
|
<span id="beat-estado" class="chip" hidden></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="controles">
|
||||||
|
<button id="btn-play" class="btn-grande btn-play" type="button">▶ Iniciar</button>
|
||||||
|
<button id="btn-stop" class="btn-grande btn-stop" type="button" hidden>■ Detener</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="volumen" for="volumen">
|
||||||
|
<span>Volumen</span>
|
||||||
|
<input id="volumen" type="range" min="-60" max="0" value="-20" step="1">
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<p id="mensaje" class="mensaje" role="alert" hidden></p>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script type="module" src="app.js"></script>
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
/* Tema oscuro, mobile-first, botones grandes. */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--fondo: #0d1117;
|
||||||
|
--panel: #161b22;
|
||||||
|
--borde: #2d333b;
|
||||||
|
--texto: #e6edf3;
|
||||||
|
--texto-suave: #8b949e;
|
||||||
|
--alpha: #58c4dc; /* calma */
|
||||||
|
--beta: #f0a83c; /* foco */
|
||||||
|
--transicion: #b083f0;
|
||||||
|
--peligro: #e5534b;
|
||||||
|
--acento: #3fb68b;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--fondo);
|
||||||
|
color: var(--texto);
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
min-height: 100dvh;
|
||||||
|
padding: env(safe-area-inset-top) env(safe-area-inset-right)
|
||||||
|
env(safe-area-inset-bottom) env(safe-area-inset-left);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cabecera { padding: 1.2rem 1.2rem 0.4rem; }
|
||||||
|
.cabecera h1 { margin: 0; font-size: 1.6rem; letter-spacing: 0.02em; }
|
||||||
|
.aviso { margin: 0.3rem 0 0; color: var(--texto-suave); font-size: 0.85rem; }
|
||||||
|
|
||||||
|
.vista { padding: 1rem 1.2rem 2rem; max-width: 480px; margin: 0 auto; }
|
||||||
|
|
||||||
|
/* ── Tarjetas de presets ── */
|
||||||
|
.tarjetas { display: grid; gap: 0.8rem; }
|
||||||
|
.cargando { color: var(--texto-suave); }
|
||||||
|
|
||||||
|
.tarjeta {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--borde);
|
||||||
|
border-radius: 14px;
|
||||||
|
padding: 1rem 1.1rem;
|
||||||
|
color: var(--texto);
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.15s;
|
||||||
|
}
|
||||||
|
.tarjeta:active { border-color: var(--acento); }
|
||||||
|
.tarjeta h3 { margin: 0 0 0.25rem; font-size: 1.15rem; text-transform: capitalize; }
|
||||||
|
.tarjeta p { margin: 0 0 0.6rem; color: var(--texto-suave); font-size: 0.9rem; }
|
||||||
|
.tarjeta .datos { display: flex; gap: 0.5rem; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
.chip {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.15rem 0.6rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
background: var(--borde);
|
||||||
|
color: var(--texto);
|
||||||
|
}
|
||||||
|
.chip.alpha { background: color-mix(in srgb, var(--alpha) 25%, transparent); color: var(--alpha); }
|
||||||
|
.chip.beta { background: color-mix(in srgb, var(--beta) 25%, transparent); color: var(--beta); }
|
||||||
|
.chip.transicion {
|
||||||
|
background: color-mix(in srgb, var(--transicion) 25%, transparent);
|
||||||
|
color: var(--transicion);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Sesión ── */
|
||||||
|
.btn-volver {
|
||||||
|
background: none; border: none; color: var(--acento);
|
||||||
|
font-size: 1rem; padding: 0.3rem 0; cursor: pointer;
|
||||||
|
}
|
||||||
|
#sesion-nombre { margin: 0.4rem 0 0.2rem; font-size: 1.4rem; text-transform: capitalize; }
|
||||||
|
.desc { margin: 0 0 1rem; color: var(--texto-suave); font-size: 0.92rem; }
|
||||||
|
|
||||||
|
.timer {
|
||||||
|
font-size: clamp(4rem, 22vw, 6.5rem);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-weight: 200;
|
||||||
|
text-align: center;
|
||||||
|
margin: 1.2rem 0 0.4rem;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.indicador {
|
||||||
|
display: flex; align-items: center; justify-content: center; gap: 0.7rem;
|
||||||
|
min-height: 2rem; margin-bottom: 1.6rem;
|
||||||
|
}
|
||||||
|
.beat-hz { color: var(--texto-suave); font-variant-numeric: tabular-nums; }
|
||||||
|
|
||||||
|
.controles { display: grid; gap: 0.8rem; }
|
||||||
|
.btn-grande {
|
||||||
|
width: 100%;
|
||||||
|
padding: 1.1rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
border: none;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
touch-action: manipulation;
|
||||||
|
}
|
||||||
|
.btn-play { background: var(--acento); color: #04160f; }
|
||||||
|
.btn-stop { background: var(--peligro); color: #fff; }
|
||||||
|
.btn-grande:disabled { opacity: 0.5; }
|
||||||
|
|
||||||
|
.volumen { display: block; margin-top: 1.6rem; color: var(--texto-suave); font-size: 0.9rem; }
|
||||||
|
.volumen input {
|
||||||
|
width: 100%; margin-top: 0.5rem; accent-color: var(--acento); height: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mensaje {
|
||||||
|
margin-top: 1rem; padding: 0.8rem 1rem; border-radius: 12px;
|
||||||
|
background: color-mix(in srgb, var(--peligro) 15%, transparent);
|
||||||
|
color: var(--peligro); font-size: 0.92rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// Criterio 10: la página carga, lista presets, Play deja el AudioContext
|
||||||
|
// en 'running' y el timer avanza.
|
||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
test('lista presets, reproduce y el timer avanza', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
|
||||||
|
const tarjetas = page.locator('.tarjeta');
|
||||||
|
await expect(tarjetas).toHaveCount(5);
|
||||||
|
await expect(tarjetas.filter({ hasText: 'estudio' })).toBeVisible();
|
||||||
|
|
||||||
|
await tarjetas.filter({ hasText: 'estudio' }).click();
|
||||||
|
await expect(page.locator('#vista-sesion')).toBeVisible();
|
||||||
|
await expect(page.locator('#timer')).toHaveText('30:00');
|
||||||
|
|
||||||
|
await page.click('#btn-play');
|
||||||
|
await expect
|
||||||
|
.poll(() => page.evaluate(() => window.__binaural.motor.ctx?.state), { timeout: 10_000 })
|
||||||
|
.toBe('running');
|
||||||
|
|
||||||
|
// Tras el pre-roll (1.5 s) la cuenta regresiva debe haberse movido.
|
||||||
|
await expect(page.locator('#timer')).not.toHaveText('30:00', { timeout: 10_000 });
|
||||||
|
await expect(page.locator('#beat-hz')).toContainText('batido', { timeout: 5_000 });
|
||||||
|
|
||||||
|
await page.click('#btn-stop');
|
||||||
|
await expect(page.locator('#btn-play')).toBeVisible();
|
||||||
|
});
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/**
|
||||||
|
* Cuenta regresiva ligada al reloj de audio (ctx.currentTime), nunca a
|
||||||
|
* setTimeout acumulado: el intervalo solo refresca la pintura.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class Temporizador {
|
||||||
|
/** @param {(datos: object) => void} alTic — recibe lo que devuelva fnEstado */
|
||||||
|
constructor(alTic) {
|
||||||
|
this.alTic = alTic;
|
||||||
|
/** @type {number|null} */
|
||||||
|
this.intervalo = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {() => object} fnEstado — lee el estado actual del motor */
|
||||||
|
iniciar(fnEstado) {
|
||||||
|
this.parar();
|
||||||
|
const tic = () => this.alTic(fnEstado());
|
||||||
|
tic();
|
||||||
|
this.intervalo = setInterval(tic, 250);
|
||||||
|
}
|
||||||
|
|
||||||
|
parar() {
|
||||||
|
if (this.intervalo !== null) {
|
||||||
|
clearInterval(this.intervalo);
|
||||||
|
this.intervalo = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user