Rework sound effects and add pre-generated Piper narration

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 12:29:51 +02:00
parent 61eccb2f80
commit 7050cb1ac6
60 changed files with 918 additions and 83 deletions
+79
View File
@@ -0,0 +1,79 @@
// Effets sonores : rendu hors ligne dans Chromium (même chaîne que la lecture réelle), puis mesure
// de la crête et du niveau efficace. Définir AUDIO_DUMP_DIR pour écrire des .wav à écouter.
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { after, before, test } from 'node:test';
import assert from 'node:assert';
import { chromium } from 'playwright-core';
const root = new URL('../../', import.meta.url).pathname;
const executablePath = process.env.CHROMIUM ?? '/usr/bin/chromium';
const port = 8128;
const skip = !existsSync(executablePath) && `navigateur absent (${executablePath})`;
const SAMPLE_RATE = 44100;
let server;
let browser;
before(async () => {
if (skip) return;
server = spawn('python3', [`${root}scripts/dev_server.py`, '--port', String(port)], { env: { ...process.env, PYQUEST_QUIET: '1' }, stdio: 'ignore' });
await new Promise((resolve) => setTimeout(resolve, 1000));
browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
});
after(async () => {
await browser?.close();
server?.kill();
});
const toDb = (value) => 20 * Math.log10(value);
function wav16(samples) {
const buffer = Buffer.alloc(44 + samples.length * 2);
buffer.write('RIFF', 0);
buffer.writeUInt32LE(36 + samples.length * 2, 4);
buffer.write('WAVEfmt ', 8);
buffer.writeUInt32LE(16, 16);
buffer.writeUInt16LE(1, 20); // PCM
buffer.writeUInt16LE(1, 22); // mono
buffer.writeUInt32LE(SAMPLE_RATE, 24);
buffer.writeUInt32LE(SAMPLE_RATE * 2, 28);
buffer.writeUInt16LE(2, 32);
buffer.writeUInt16LE(16, 34);
buffer.write('data', 36);
buffer.writeUInt32LE(samples.length * 2, 40);
samples.forEach((value, index) => buffer.writeInt16LE(Math.round(Math.max(-1, Math.min(1, value)) * 32767), 44 + index * 2));
return buffer;
}
test('les effets sonores sont audibles, sans saturation', { skip, timeout: 60000 }, async () => {
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${port}/`);
const rendered = await page.evaluate(async (rate) => {
const { AudioEngine } = await import('/js/core/AudioEngine.js');
const sounds = {};
for (const name of AudioEngine.soundNames) {
const context = new OfflineAudioContext(1, rate * 3, rate);
const { input } = AudioEngine.buildOutput(context, 0.8); // volume par défaut des réglages
const duration = AudioEngine.schedule(context, input, name, 0);
const buffer = await context.startRendering();
sounds[name] = Array.from(buffer.getChannelData(0).slice(0, Math.ceil(duration * rate)));
}
return sounds;
}, SAMPLE_RATE);
const dump = process.env.AUDIO_DUMP_DIR;
if (dump) mkdirSync(dump, { recursive: true });
for (const [name, samples] of Object.entries(rendered)) {
const peak = Math.max(...samples.map(Math.abs));
const active = samples.filter((value) => Math.abs(value) > 0.001);
const rms = Math.sqrt(active.reduce((sum, value) => sum + value * value, 0) / active.length);
console.log(`${name.padEnd(15)} durée ${(samples.length / SAMPLE_RATE).toFixed(2)} s crête ${toDb(peak).toFixed(1)} dBFS efficace ${toDb(rms).toFixed(1)} dBFS`);
if (dump) writeFileSync(`${dump}/fx-${name}.wav`, wav16(samples));
// Audible : crête au moins -8 dBFS, niveau efficace au moins -26 dBFS ; jamais de saturation.
assert.ok(toDb(peak) >= -8, `${name} trop faible : crête ${toDb(peak).toFixed(1)} dBFS`);
assert.ok(toDb(peak) <= -0.5, `${name} sature : crête ${toDb(peak).toFixed(1)} dBFS`);
assert.ok(toDb(rms) >= -26, `${name} trop faible : efficace ${toDb(rms).toFixed(1)} dBFS`);
}
});
+47
View File
@@ -145,3 +145,50 @@ test('niveau 03 : saisie interactive et validation par rejeu scripté', { skip,
assert.deepEqual(errors, []);
});
test('narration : fichier Piper lu jusqu\'au bout, échantillon des réglages, repli', { skip, timeout: 120000 }, async () => {
const browser2 = await chromium.launch({ executablePath, args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] });
try {
const page = await (await browser2.newContext()).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const served = [];
page.on('response', (response) => {
if (response.url().endsWith('.mp3')) served.push(`${response.status()} ${response.headers()['content-type']}`);
});
// Espionne les lectures pour savoir si un fichier est allé jusqu'à la fin.
await page.addInitScript(() => {
window.__audio = { ended: 0, errors: 0 };
const Original = window.Audio;
window.Audio = class extends Original {
constructor(...args) {
super(...args);
this.addEventListener('ended', () => (window.__audio.ended += 1));
this.addEventListener('error', () => (window.__audio.errors += 1));
}
};
});
await page.goto(base);
await page.waitForSelector('.explain', { timeout: 60000 });
// La voix est désactivée par défaut : pas de bouton « Écouter ».
assert.equal(await page.locator('.explain button', { hasText: 'Écouter' }).count(), 0);
await page.locator('#settings-toggle').click();
await page.getByLabel('Voix', { exact: true }).check();
await page.locator('.settings').getByRole('button', { name: 'Tester la voix' }).click();
await page.waitForFunction(() => window.__audio.ended >= 1, null, { timeout: 30000 });
// Narration d'une étape de niveau : relance le niveau pour afficher le bouton.
await page.locator('.level-button', { hasText: 'Ton premier programme' }).click();
await page.waitForSelector('.explain button');
const before = await page.evaluate(() => window.__audio.ended);
await page.locator('.explain button', { hasText: 'Écouter' }).click();
await page.waitForFunction((count) => window.__audio.ended > count, before, { timeout: 30000 });
assert.ok(served.length >= 2 && served.every((entry) => entry.startsWith('200 audio/mpeg')), `mp3 servis : ${served}`);
assert.equal(await page.evaluate(() => window.__audio.errors), 0);
assert.deepEqual(errors, []);
} finally {
await browser2.close();
}
});
+27 -4
View File
@@ -2,12 +2,13 @@ import { AudioEngine } from '../../app/js/core/AudioEngine.js';
import { VoiceEngine } from '../../app/js/core/VoiceEngine.js';
import assert from 'node:assert';
let osc = 0;
const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: {}, gain: { setValueAtTime() {}, linearRampToValueAtTime() {} } });
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node };
const param = () => ({ value: 0, setValueAtTime() {}, linearRampToValueAtTime() {}, exponentialRampToValueAtTime() {} });
const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: param(), gain: param(), threshold: param(), knee: param(), ratio: param(), attack: param(), release: param() });
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node, createDynamicsCompressor: node };
const a = new AudioEngine({ contextFactory: () => ctx });
assert.equal(a.play('success_small'), false); // pas débloqué
await a.unlock();
assert.equal(a.play('success_small'), true); assert.equal(osc, 2);
assert.equal(a.play('success_small'), true); assert.equal(osc, 6); // 2 notes × 3 partiels
assert.equal(a.play('nope'), false);
a.setEnabled(false); assert.equal(a.play('error'), false);
a.setEnabled(true); a.setVolume(5); assert.equal(a.volume, 1);
@@ -21,5 +22,27 @@ assert.equal(await v.speak('Utilise `print()` ici', 'fr'), true);
const u = spoken.at(-1); assert.equal(u.text, 'Utilise print() ici'); assert.equal(u.voice.lang, 'fr-FR'); assert.equal(u.lang, 'fr-FR');
v.setRate(9); assert.equal(v.rate, 2);
v.setEnabled(false); assert.equal(await v.speak('x'), false);
assert.equal(new VoiceEngine({ synth: null, Utterance: undefined }).supported, false);
assert.equal(new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined }).supported, false);
// Narration par fichier pré-généré, avec repli sur la voix système si le fichier manque.
globalThis.URL.createObjectURL = () => 'blob:fake';
globalThis.URL.revokeObjectURL = () => {};
const played = [];
class FakeAudio {
constructor(src) { this.src = src; played.push(this); }
play() { queueMicrotask(() => { this.onplaying?.(); this.onended?.(); }); return Promise.resolve(); }
pause() {}
}
const spoken2 = [];
const synth2 = { cancel() {}, getVoices: () => [], speak(u) { spoken2.push(u.text); setTimeout(() => u.onend(), 0); } };
const files = { ok: true };
const fetchFn = async (url) => (url.endsWith('/there.mp3') ? { ok: true, blob: async () => new Blob(['x']) } : { ok: false });
const v2 = new VoiceEngine({ synth: synth2, Utterance: U, AudioClass: FakeAudio, fetchFn });
assert.equal(await v2.speak('Texte', 'fr', { audioUrl: '/a/there.mp3' }), true);
assert.equal(played.length, 1); assert.deepEqual(spoken2, []); // fichier lu, pas de voix système
assert.equal(await v2.speak('Repli `x`', 'fr', { audioUrl: '/a/absent.mp3' }), true);
assert.equal(played.length, 1); assert.deepEqual(spoken2, ['Repli x']); // fichier absent : repli
v2.setRate(1.5); assert.equal(v2.rate, 1.5);
const noAudioNoSynth = new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined });
assert.equal(noAudioNoSynth.supported, false);
console.log('audio/voice ok');
+10
View File
@@ -0,0 +1,10 @@
// Vecteurs communs avec tests/python/test_voice_key.py : les deux implémentations doivent concorder.
import { speechKey, speechText } from '../../app/js/core/speechKey.js';
import assert from 'node:assert';
assert.equal(speechText(' Un `print()` affiche\n du texte. '), 'Un print() affiche du texte.');
assert.equal(speechKey('fr', 'Un `print()` affiche du texte.'), '0933ff041539352b');
assert.equal(speechKey('en', 'Héllo wörld'), '87e2e25e5123e565');
assert.equal(speechKey('fr', ''), 'dc8d3218feba4761');
assert.notEqual(speechKey('fr', 'Bonjour'), speechKey('en', 'Bonjour'));
console.log('speech key ok');
+36
View File
@@ -0,0 +1,36 @@
// Chaque étape narrée de chaque niveau doit avoir son fichier audio (make voice), dans les deux
// langues, à l'URL exacte que construit LevelSession ; idem pour l'échantillon des réglages.
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import assert from 'node:assert';
import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs';
import { LevelSession } from '../../app/js/core/LevelSession.js';
import { speechKey } from '../../app/js/core/speechKey.js';
const root = new URL('../../', import.meta.url).pathname;
const base = 'http://x/levels/';
const missing = [];
let checked = 0;
for (const id of readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name))) {
const level = yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
for (const lang of ['fr', 'en']) {
const session = new LevelSession(level, lang, `${base}${id}/`);
for (let i = 0; i < session.stepCount; i++, session.next()) {
const step = session.step;
if (step.type !== 'explain' || !step.voice) continue;
checked += 1;
assert.ok(step.audioUrl.startsWith(`${base}${id}/audio/${lang}/`), step.audioUrl);
const file = `${root}levels/${step.audioUrl.slice(base.length)}`;
if (!existsSync(file)) missing.push(file);
}
}
}
for (const lang of ['fr', 'en']) {
const sample = JSON.parse(readFileSync(`${root}app/js/i18n/${lang}.json`, 'utf8'))['voice.sample'];
const file = `${root}app/assets/voice/${lang}/${speechKey(lang, sample)}.mp3`;
checked += 1;
if (!existsSync(file)) missing.push(file);
}
assert.ok(checked > 0);
assert.deepEqual(missing, [], 'narration manquante : lancer make voice');
console.log(`voice assets ok (${checked} fichiers)`);
+28
View File
@@ -0,0 +1,28 @@
"""Vecteurs communs avec tests/js/speech-key.test.mjs : les deux implémentations doivent concorder."""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
from voice_key import speech_key, speech_text # noqa: E402
class VoiceKeyTest(unittest.TestCase):
def test_text_is_normalised(self) -> None:
self.assertEqual(speech_text(" Un `print()` affiche\n du texte. "), "Un print() affiche du texte.")
def test_vectors_match_javascript(self) -> None:
self.assertEqual(speech_key("fr", "Un `print()` affiche du texte."), "0933ff041539352b")
self.assertEqual(speech_key("en", "Héllo wörld"), "87e2e25e5123e565")
self.assertEqual(speech_key("fr", ""), "dc8d3218feba4761")
def test_language_changes_key(self) -> None:
self.assertNotEqual(speech_key("fr", "Bonjour"), speech_key("en", "Bonjour"))
if __name__ == "__main__":
unittest.main()