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
+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');
}