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
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
{
"en": {
"23087e367ecc886e": {
"text": "Hello, I am the voice of PyQuest. This is how I will read the explanations.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"c4262bd49831c690": {
"text": "Bonjour, je suis la voix de PyQuest. Voici comment je lirai les explications.",
"voice": "fr_FR-siwis-medium"
}
}
}
+95 -34
View File
@@ -1,37 +1,61 @@
// Effets sonores courts via Web Audio API, synthétisés (aucun fichier audio à servir ni à licencier).
// Toujours désactivable ; jamais déclenché avant un geste utilisateur (contrainte autoplay iOS).
//
// Timbre : synthèse additive (fondamentale + 2 harmoniques, sinusoïdes) avec une attaque nette et
// une extinction exponentielle, pour un son de « carillon » doux plutôt que des ondes brutes.
// Niveau : un gain maître puis un compresseur ramènent tous les sons à un volume comparable et
// audible sans saturer (voir tests/e2e : mesure de crête et de niveau efficace).
// Chaque son est une suite de notes : fréquence (Hz), début et durée (s), forme d'onde.
// Partiels d'un timbre : [multiple de la fréquence, amplitude relative].
const BELL = [
[1, 1],
[2, 0.35],
[3, 0.12],
];
const SOFT = [
[1, 1],
[2, 0.5],
];
// Chaque note : fréquence (Hz), début et durée (s), gain relatif (accords : < 1), timbre.
const SOUNDS = {
success_small: [
{ frequency: 659.25, start: 0, duration: 0.12, type: 'sine' },
{ frequency: 880, start: 0.1, duration: 0.2, type: 'sine' },
{ frequency: 659.25, start: 0, duration: 0.3, gain: 0.9, timbre: BELL },
{ frequency: 880, start: 0.11, duration: 0.5, gain: 1, timbre: BELL },
],
success_big: [
{ frequency: 523.25, start: 0, duration: 0.12, type: 'triangle' },
{ frequency: 659.25, start: 0.12, duration: 0.12, type: 'triangle' },
{ frequency: 783.99, start: 0.24, duration: 0.12, type: 'triangle' },
{ frequency: 1046.5, start: 0.36, duration: 0.35, type: 'triangle' },
{ frequency: 523.25, start: 0, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 659.25, start: 0.12, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 783.99, start: 0.24, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 1046.5, start: 0.36, duration: 0.9, gain: 0.6, timbre: BELL },
{ frequency: 783.99, start: 0.36, duration: 0.9, gain: 0.5, timbre: BELL },
{ frequency: 523.25, start: 0.36, duration: 0.9, gain: 0.5, timbre: BELL },
],
level_unlocked: [
{ frequency: 392, start: 0, duration: 0.15, type: 'square' },
{ frequency: 523.25, start: 0.15, duration: 0.15, type: 'square' },
{ frequency: 659.25, start: 0.3, duration: 0.15, type: 'square' },
{ frequency: 783.99, start: 0.45, duration: 0.15, type: 'square' },
{ frequency: 1046.5, start: 0.6, duration: 0.5, type: 'square' },
{ frequency: 392, start: 0, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 523.25, start: 0.14, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 659.25, start: 0.28, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 783.99, start: 0.42, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 1046.5, start: 0.56, duration: 1.2, gain: 0.6, timbre: BELL },
{ frequency: 783.99, start: 0.56, duration: 1.2, gain: 0.45, timbre: BELL },
{ frequency: 659.25, start: 0.56, duration: 1.2, gain: 0.45, timbre: BELL },
],
error: [
{ frequency: 220, start: 0, duration: 0.18, type: 'sawtooth' },
{ frequency: 174.61, start: 0.15, duration: 0.25, type: 'sawtooth' },
{ frequency: 293.66, start: 0, duration: 0.25, gain: 0.9, timbre: SOFT },
{ frequency: 220, start: 0.16, duration: 0.45, gain: 1, timbre: SOFT },
],
};
// Les sons « square » et « sawtooth » sont agressifs : gain de base réduit.
const BASE_GAIN = 0.15;
const ATTACK_S = 0.008;
const SILENCE = 0.0001; // cible de l'extinction exponentielle (ne peut pas valoir 0)
// Niveau de crête d'une note de gain 1 avant compresseur : laisse de la marge aux accords.
const NOTE_PEAK = 0.45;
export class AudioEngine {
#createContext;
#context = null;
#master = null;
#output = null;
#enabled;
#volume;
@@ -56,6 +80,51 @@ export class AudioEngine {
return Object.keys(SOUNDS);
}
/**
* Construit la chaîne de sortie (gain maître → compresseur → sortie) et renvoie ses nœuds.
* Exposé pour que les tests rendent les sons hors ligne avec exactement la même chaîne.
*/
static buildOutput(context, volume) {
const master = context.createGain();
master.gain.value = volume;
const compressor = context.createDynamicsCompressor();
compressor.threshold.value = -14;
compressor.knee.value = 10;
compressor.ratio.value = 6;
compressor.attack.value = 0.003;
compressor.release.value = 0.2;
master.connect(compressor).connect(context.destination);
return { input: master, master };
}
/**
* Programme les notes d'un son sur `destination`, à partir de `when`.
* @returns {number} durée totale en secondes (queue d'extinction comprise)
*/
static schedule(context, destination, name, when = context.currentTime) {
let end = 0;
for (const note of SOUNDS[name]) {
const noteStart = when + note.start;
const noteEnd = noteStart + note.duration;
const peak = NOTE_PEAK * note.gain;
for (const [multiple, amplitude] of note.timbre) {
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.type = 'sine';
oscillator.frequency.value = note.frequency * multiple;
// Attaque courte (pas de clic), puis extinction exponentielle.
gain.gain.setValueAtTime(0, noteStart);
gain.gain.linearRampToValueAtTime(peak * amplitude, noteStart + ATTACK_S);
gain.gain.exponentialRampToValueAtTime(SILENCE, noteEnd);
oscillator.connect(gain).connect(destination);
oscillator.start(noteStart);
oscillator.stop(noteEnd + 0.02);
}
end = Math.max(end, note.start + note.duration + 0.02);
}
return end;
}
get enabled() {
return this.#enabled;
}
@@ -75,6 +144,9 @@ export class AudioEngine {
setVolume(volume) {
this.#volume = Math.min(1, Math.max(0, volume));
if (this.#master) {
this.#master.gain.value = this.#volume;
}
}
/**
@@ -84,6 +156,11 @@ export class AudioEngine {
async unlock() {
if (!this.#context) {
this.#context = this.#createContext();
if (this.#context) {
const output = AudioEngine.buildOutput(this.#context, this.#volume);
this.#master = output.master;
this.#output = output.input;
}
}
if (this.#context?.state === 'suspended') {
await this.#context.resume();
@@ -96,26 +173,10 @@ export class AudioEngine {
* @returns {boolean} vrai si le son a été lancé
*/
play(name) {
const notes = SOUNDS[name];
if (!this.#enabled || !this.#context || this.#context.state !== 'running' || !notes) {
if (!this.#enabled || !this.#context || this.#context.state !== 'running' || !SOUNDS[name]) {
return false;
}
const context = this.#context;
const now = context.currentTime;
for (const note of notes) {
const oscillator = context.createOscillator();
const gain = context.createGain();
const peak = BASE_GAIN * this.#volume;
oscillator.type = note.type;
oscillator.frequency.value = note.frequency;
// Enveloppe courte pour éviter les clics de début et de fin.
gain.gain.setValueAtTime(0, now + note.start);
gain.gain.linearRampToValueAtTime(peak, now + note.start + 0.01);
gain.gain.linearRampToValueAtTime(0, now + note.start + note.duration);
oscillator.connect(gain).connect(context.destination);
oscillator.start(now + note.start);
oscillator.stop(now + note.start + note.duration + 0.02);
}
AudioEngine.schedule(this.#context, this.#output, name);
return true;
}
}
+9
View File
@@ -1,5 +1,7 @@
// Parcours d'un niveau par l'apprenant : étapes localisées puis mission finale.
import { speechKey } from './speechKey.js';
export class LevelSession {
#level;
#lang;
@@ -77,6 +79,11 @@ export class LevelSession {
return true;
}
#audioUrl(step) {
const lang = step.text[this.#lang] ? this.#lang : 'fr';
return new URL(`audio/${lang}/${speechKey(lang, step.text[lang])}.mp3`, this.#baseUrl).href;
}
#localize(value) {
return value?.[this.#lang] ?? value?.fr ?? '';
}
@@ -95,6 +102,8 @@ export class LevelSession {
text: this.#localize(step.text),
voice: step.voice ?? false,
image: step.image ? new URL(step.image, this.#baseUrl).href : null,
// Narration pré-générée (make voice) ; absente = repli sur la voix du système.
audioUrl: step.voice ? this.#audioUrl(step) : null,
};
}
return {
+106 -12
View File
@@ -1,13 +1,20 @@
// Narration vocale optionnelle via speechSynthesis (voix du système, aucun service tiers).
// À appeler uniquement depuis un geste utilisateur (bouton « Écouter »), jamais automatiquement.
// Narration vocale optionnelle, à appeler uniquement depuis un geste utilisateur (bouton « Écouter »).
// 1) fichier audio pré-généré avec Piper (make voice) : même qualité partout, hors ligne ;
// 2) repli : speechSynthesis (voix du système) si le fichier est absent ou illisible.
// Aucun service tiers.
const LANG_TAGS = { fr: 'fr-FR', en: 'en-US' };
export class VoiceEngine {
#synth;
#UtteranceClass;
#AudioClass;
#fetch;
#enabled;
#rate;
#audio = null;
#objectUrl = null;
#session = 0;
/**
* @param {object} [options]
@@ -15,22 +22,28 @@ export class VoiceEngine {
* @param {number} [options.rate] Vitesse de 0.5 à 2 (1 = normale).
* @param {SpeechSynthesis|null} [options.synth] Remplaçable pour les tests.
* @param {typeof SpeechSynthesisUtterance} [options.Utterance]
* @param {typeof Audio|undefined} [options.AudioClass]
* @param {typeof fetch} [options.fetchFn]
*/
constructor({
enabled = true,
rate = 1,
synth = globalThis.speechSynthesis ?? null,
Utterance = globalThis.SpeechSynthesisUtterance,
AudioClass = globalThis.Audio,
fetchFn = (...args) => fetch(...args),
} = {}) {
this.#synth = synth;
this.#UtteranceClass = Utterance;
this.#AudioClass = AudioClass;
this.#fetch = fetchFn;
this.#enabled = enabled;
this.#rate = rate;
}
/** Faux sur les navigateurs sans speechSynthesis : l'UI masque alors le bouton. */
/** Faux si ni fichier audio ni speechSynthesis ne sont utilisables : l'UI masque le bouton. */
get supported() {
return this.#synth !== null && this.#UtteranceClass !== undefined;
return this.#AudioClass !== undefined || (this.#synth !== null && this.#UtteranceClass !== undefined);
}
get enabled() {
@@ -50,19 +63,104 @@ export class VoiceEngine {
setRate(rate) {
this.#rate = Math.min(2, Math.max(0.5, rate));
if (this.#audio) {
this.#audio.playbackRate = this.#rate;
}
}
/**
* Lit un texte. Résout à la fin de la lecture ; false si rien n'a été lu.
* @param {string} text Markdown léger toléré (les `` ` `` sont retirés).
* Lit un texte. Résout à la fin de la lecture ; false si rien n'a été lu ou si elle a été interrompue.
* @param {string} text Markdown léger toléré (les `` ` `` sont retirés pour la synthèse système).
* @param {string} [lang] 'fr' ou 'en'.
* @param {object} [options]
* @param {string|null} [options.audioUrl] Fichier pré-généré à préférer à la synthèse système.
* @returns {Promise<boolean>}
*/
speak(text, lang = 'fr') {
async speak(text, lang = 'fr', { audioUrl = null } = {}) {
if (!this.supported || !this.#enabled) {
return Promise.resolve(false);
return false;
}
this.cancel();
const session = this.#session;
if (audioUrl && this.#AudioClass) {
const played = await this.#playFile(audioUrl, session);
if (played !== null) {
return played;
}
}
if (session !== this.#session) {
return false;
}
return this.#speakWithSystemVoice(text, lang);
}
/** Interrompt toute lecture en cours (fichier ou synthèse). */
cancel() {
this.#session += 1;
this.#releaseAudio();
this.#synth?.cancel();
}
/**
* Joue un fichier audio. Renvoie true (terminé), false (interrompu) ou null si le fichier est
* indisponible, auquel cas l'appelant se rabat sur la voix système.
*/
async #playFile(url, session) {
let blob;
try {
const response = await this.#fetch(url);
if (!response.ok) {
return null;
}
blob = await response.blob();
} catch {
return null;
}
if (session !== this.#session) {
return false;
}
// Lecture depuis un blob : pas de requêtes Range (exigées par iOS pour un flux direct).
this.#objectUrl = URL.createObjectURL(blob);
const audio = new this.#AudioClass(this.#objectUrl);
audio.playbackRate = this.#rate;
this.#audio = audio;
return new Promise((resolve) => {
let started = false;
audio.onplaying = () => {
started = true;
};
audio.onended = () => {
this.#releaseAudio();
resolve(true);
};
audio.onpause = () => resolve(false);
audio.onerror = () => {
this.#releaseAudio();
resolve(started ? false : null);
};
Promise.resolve(audio.play()).catch(() => {
this.#releaseAudio();
resolve(null);
});
});
}
#releaseAudio() {
if (this.#audio) {
this.#audio.onpause = null;
this.#audio.pause?.();
this.#audio = null;
}
if (this.#objectUrl) {
URL.revokeObjectURL(this.#objectUrl);
this.#objectUrl = null;
}
}
#speakWithSystemVoice(text, lang) {
if (this.#synth === null || this.#UtteranceClass === undefined) {
return Promise.resolve(false);
}
const utterance = new this.#UtteranceClass(this.#clean(text));
utterance.lang = LANG_TAGS[lang] ?? lang;
utterance.rate = this.#rate;
@@ -78,10 +176,6 @@ export class VoiceEngine {
});
}
cancel() {
this.#synth?.cancel();
}
/** Voix du système correspondant à la langue, en privilégiant l'étiquette exacte. */
#pickVoice(tag) {
const voices = this.#synth.getVoices?.() ?? [];
+20
View File
@@ -0,0 +1,20 @@
// Clé de narration : relie un texte de niveau à son fichier audio pré-généré.
// Doit rester strictement identique à scripts/voice_key.py (vecteurs de test communs).
const FNV_OFFSET = 0xcbf29ce484222325n;
const FNV_PRIME = 0x100000001b3n;
const MASK = 0xffffffffffffffffn;
/** Texte réellement lu : sans backticks Markdown, espaces normalisés. */
export function speechText(text) {
return text.replace(/`/g, '').replace(/\s+/g, ' ').trim();
}
/** Empreinte FNV-1a 64 bits (16 caractères hexadécimaux) de la langue et du texte lu. */
export function speechKey(lang, text) {
let value = FNV_OFFSET;
for (const byte of new TextEncoder().encode(`${lang}\n${speechText(text)}`)) {
value = ((value ^ BigInt(byte)) * FNV_PRIME) & MASK;
}
return value.toString(16).padStart(16, '0');
}
+4
View File
@@ -59,5 +59,9 @@
"settings.sound": "Sound effects",
"settings.volume": "Volume",
"settings.voice": "Voice",
"voice.sample": "Hello, I am the voice of PyQuest. This is how I will read the explanations.",
"settings.testSound": "Test the sound",
"settings.testVoice": "Test the voice",
"settings.voiceOffNotice": "Turn the voice on in the settings first.",
"settings.voiceRate": "Voice speed"
}
+4
View File
@@ -59,5 +59,9 @@
"settings.sound": "Effets sonores",
"settings.volume": "Volume",
"settings.voice": "Voix",
"voice.sample": "Bonjour, je suis la voix de PyQuest. Voici comment je lirai les explications.",
"settings.testSound": "Tester le son",
"settings.testVoice": "Tester la voix",
"settings.voiceOffNotice": "Active d'abord la voix dans les réglages.",
"settings.voiceRate": "Vitesse de la voix"
}
+22 -1
View File
@@ -10,6 +10,7 @@ import { SettingsStore } from './core/SettingsStore.js';
import { ValidationEngine } from './core/ValidationEngine.js';
import { VoiceEngine } from './core/VoiceEngine.js';
import { I18n } from './i18n/i18n.js';
import { speechKey } from './core/speechKey.js';
import { BadgeToast } from './ui/BadgeToast.js';
import { CellManager } from './ui/CellManager.js';
import { NotebookView } from './ui/NotebookView.js';
@@ -56,6 +57,7 @@ class App {
#audio;
#voice;
#manager;
#toast;
#map;
#panel;
#levelIds = [];
@@ -81,10 +83,11 @@ class App {
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
const notebook = new NotebookView(this.#i18n, {
onSpeak: (text) => this.#voice.speak(text, this.#i18n.lang),
onSpeak: (text, step) => this.#voice.speak(text, this.#i18n.lang, { audioUrl: step.audioUrl }),
canSpeak: () => this.#voice.supported && this.#voice.enabled,
});
const toast = new BadgeToast(this.#i18n);
this.#toast = toast;
this.#manager = new CellManager({
i18n: this.#i18n,
notebook,
@@ -101,6 +104,7 @@ class App {
this.#map.addEventListener('select', (event) => this.#openLevel(event.detail.id));
this.#panel = new SettingsPanel(this.#i18n);
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
document.getElementById('progress-region').append(this.#map.element);
document.getElementById('notebook-region').append(notebook.element);
@@ -168,6 +172,23 @@ class App {
}
}
/** Échantillons des réglages : le clic est le geste utilisateur qui débloque le son. */
async #onTest(kind) {
if (kind === 'sound') {
await this.#audio.unlock();
this.#audio.play('success_big');
return;
}
if (!this.#voice.enabled) {
this.#toast.show(this.#i18n.t('settings.voiceOffNotice'));
return;
}
const lang = this.#i18n.lang;
const sample = this.#i18n.t('voice.sample');
const audioUrl = new URL(`assets/voice/${lang}/${speechKey(lang, sample)}.mp3`, document.baseURI).href;
await this.#voice.speak(sample, lang, { audioUrl });
}
#registerServiceWorker() {
// Repli : sans service worker (http hors localhost, navigateur ancien), l'app fonctionne en ligne.
if ('serviceWorker' in navigator) {
+4 -3
View File
@@ -12,7 +12,7 @@ export class NotebookView {
/**
* @param {import('../i18n/i18n.js').I18n} i18n
* @param {object} [options]
* @param {(text: string) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton.
* @param {(text: string, step: object) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton.
* @param {() => boolean} [options.canSpeak] Évalué à chaque étape : la voix est-elle activée ?
*/
constructor(i18n, { onSpeak = null, canSpeak = () => true } = {}) {
@@ -48,13 +48,14 @@ export class NotebookView {
}
/** Étape d'explication : texte, et bouton de lecture si la voix est demandée par le niveau. */
addExplain({ text, voice, image }) {
addExplain(step) {
const { text, voice, image } = step;
const children = [el('p', {}, renderInline(text))];
if (image) {
children.push(el('img', { src: image, alt: '' }));
}
if (voice && this.#onSpeak && this.#canSpeak()) {
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text) }));
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text, step) }));
}
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
}
+14 -1
View File
@@ -1,5 +1,6 @@
// Panneau de réglages : accessible au clavier, chaque champ a un label visible.
// Émet 'change' (detail: { key, value }) ; l'application persiste et applique.
// Émet 'change' (detail: { key, value }) et 'test' (detail: { kind: 'sound' | 'voice' }) ;
// l'application persiste, applique, et joue les échantillons.
import { el, uniqueId } from './dom.js';
@@ -35,12 +36,24 @@ export class SettingsPanel extends EventTarget {
key: 'theme',
}),
this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }),
this.#testButton('settings.testSound', 'sound'),
this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }),
this.#field('settings.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }),
this.#testButton('settings.testVoice', 'voice'),
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
);
}
#testButton(labelKey, kind) {
const button = el('button', {
type: 'button',
class: 'btn',
text: this.#i18n.t(labelKey),
onclick: () => this.dispatchEvent(new CustomEvent('test', { detail: { kind } })),
});
return el('div', { class: 'setting' }, button);
}
#field(labelKey, kind, { value, options = [], key, number = false, ...range }) {
const id = uniqueId('setting');
const emit = (newValue) => this.dispatchEvent(new CustomEvent('change', { detail: { key, value: newValue } }));