mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Fix voice playback: stale service worker code, button visibility, autoplay priming
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+13
-2
@@ -70,8 +70,9 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
||||
`levels/AUDIO-CREDITS.md`. `make check-voice` (dans `make test`) détecte un fichier manquant.
|
||||
- **À faire** : l'utilisateur doit écouter effets et voix (la qualité perçue ne se mesure pas) ;
|
||||
ajuster gain/timbre (`NOTE_PEAK`, `BELL`, compresseur) ou voix/débit (`VOICES`, `LENGTH_SCALE`
|
||||
dans `scripts/generate_voice.py`) selon son retour. La voix est **désactivée par défaut**
|
||||
(réglage « Voix ») : à reconsidérer. Piper = GPL-3.0 mais outil de build seulement.
|
||||
dans `scripts/generate_voice.py`) selon son retour. La voix est **activée par défaut**
|
||||
(le bouton « Écouter » ne lit jamais seul) ; le réglage « Voix » masque/affiche les boutons
|
||||
immédiatement. Piper = GPL-3.0 mais outil de build seulement.
|
||||
- Whisper (dictée) et pyannote (diarisation) : écartés (hors besoin ; pyannote = modèles à accès
|
||||
restreint). Whisper reste une option d'accessibilité lointaine (dicter une réponse à `input()`).
|
||||
2. **Niveaux 04 à 14** (tableau dans `docs/design/05-curriculum.md`). Méthode : écrire le YAML
|
||||
@@ -105,6 +106,16 @@ Contrôle d'un son/UI à la main : `make dev` puis ouvrir l'URL dans un navigate
|
||||
|
||||
## Pièges rencontrés (à ne pas redécouvrir)
|
||||
|
||||
- **Service worker et code périmé** (bug réel, 2026-10-16) : le SW servait le JS « cache d'abord »
|
||||
avec un nom de cache constant → en dev, le navigateur gardait l'ancien code (l'utilisateur ne
|
||||
voyait ni la nouvelle voix ni les correctifs). Désormais : réseau d'abord pour tout sauf
|
||||
`/vendor/pyodide/`. En cas de doute chez un utilisateur : DevTools → Application → Service
|
||||
Workers → Unregister + Clear site data, ou recharger deux fois. Bumper `CACHE_VERSION` purge
|
||||
l'ancien cache à l'activation.
|
||||
- **Lecture audio et activation utilisateur** : `play()` après un `await fetch` peut être refusé
|
||||
(Safari/iOS surtout). `VoiceEngine` « amorce » l'élément audio avec un silence dans le clic, puis
|
||||
change la source. Les tests e2e tournent sans option d'autoplay pour rester réalistes.
|
||||
|
||||
- Node lit un `.js` sans `package.json` en CommonJS : pour tester un fichier avec classes à champs
|
||||
privés, passer par une copie `.mjs` ou importer depuis un test `.mjs` (les imports ESM
|
||||
fonctionnent via détection de syntaxe, mais `node --check fichier.js` échoue).
|
||||
|
||||
@@ -8,7 +8,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
|
||||
theme: 'auto', // 'auto' | 'light' | 'dark'
|
||||
soundEnabled: true,
|
||||
volume: 0.8,
|
||||
voiceEnabled: false,
|
||||
voiceEnabled: true, // le bouton « Écouter » ne lit jamais automatiquement : un clic à chaque fois
|
||||
voiceRate: 1,
|
||||
});
|
||||
|
||||
|
||||
+46
-11
@@ -4,6 +4,8 @@
|
||||
// Aucun service tiers.
|
||||
|
||||
const LANG_TAGS = { fr: 'fr-FR', en: 'en-US' };
|
||||
// WAV silencieux minimal : sert à « amorcer » l'élément audio pendant le clic (voir #prime).
|
||||
const SILENT_WAV = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=';
|
||||
|
||||
export class VoiceEngine {
|
||||
#synth;
|
||||
@@ -12,9 +14,10 @@ export class VoiceEngine {
|
||||
#fetch;
|
||||
#enabled;
|
||||
#rate;
|
||||
#audio = null;
|
||||
#player = null;
|
||||
#objectUrl = null;
|
||||
#session = 0;
|
||||
#lastFailure = null;
|
||||
|
||||
/**
|
||||
* @param {object} [options]
|
||||
@@ -54,6 +57,11 @@ export class VoiceEngine {
|
||||
return this.#rate;
|
||||
}
|
||||
|
||||
/** null, ou 'unavailable' si la dernière lecture demandée n'a rien pu jouer (à signaler à l'apprenant). */
|
||||
get lastFailure() {
|
||||
return this.#lastFailure;
|
||||
}
|
||||
|
||||
setEnabled(enabled) {
|
||||
this.#enabled = enabled;
|
||||
if (!enabled) {
|
||||
@@ -63,8 +71,8 @@ export class VoiceEngine {
|
||||
|
||||
setRate(rate) {
|
||||
this.#rate = Math.min(2, Math.max(0.5, rate));
|
||||
if (this.#audio) {
|
||||
this.#audio.playbackRate = this.#rate;
|
||||
if (this.#player) {
|
||||
this.#player.playbackRate = this.#rate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,21 +85,45 @@ export class VoiceEngine {
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async speak(text, lang = 'fr', { audioUrl = null } = {}) {
|
||||
this.#lastFailure = null;
|
||||
if (!this.supported || !this.#enabled) {
|
||||
return false;
|
||||
}
|
||||
this.cancel();
|
||||
// Doit s'exécuter de façon synchrone dans le gestionnaire de clic, avant tout await.
|
||||
this.#prime();
|
||||
const session = this.#session;
|
||||
// Une lecture interrompue (nouvelle demande, annulation) n'est pas une panne.
|
||||
const finish = (ok) => {
|
||||
if (!ok && session === this.#session) {
|
||||
this.#lastFailure = 'unavailable';
|
||||
}
|
||||
return ok;
|
||||
};
|
||||
if (audioUrl && this.#AudioClass) {
|
||||
const played = await this.#playFile(audioUrl, session);
|
||||
if (played !== null) {
|
||||
return played;
|
||||
return finish(played);
|
||||
}
|
||||
}
|
||||
if (session !== this.#session) {
|
||||
return false;
|
||||
}
|
||||
return this.#speakWithSystemVoice(text, lang);
|
||||
return finish(await this.#speakWithSystemVoice(text, lang));
|
||||
}
|
||||
|
||||
/**
|
||||
* Débloque l'élément audio pendant le geste utilisateur. Safari/iOS n'autorise la lecture
|
||||
* que si l'élément a été démarré par un geste ; or le fichier n'arrive qu'après un fetch
|
||||
* asynchrone. On joue donc un silence tout de suite, puis on change la source plus tard.
|
||||
*/
|
||||
#prime() {
|
||||
if (!this.#AudioClass) {
|
||||
return;
|
||||
}
|
||||
this.#player ??= new this.#AudioClass();
|
||||
this.#player.src = SILENT_WAV;
|
||||
Promise.resolve(this.#player.play()).catch(() => {});
|
||||
}
|
||||
|
||||
/** Interrompt toute lecture en cours (fichier ou synthèse). */
|
||||
@@ -121,9 +153,9 @@ export class VoiceEngine {
|
||||
}
|
||||
// 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);
|
||||
const audio = this.#player;
|
||||
audio.src = this.#objectUrl;
|
||||
audio.playbackRate = this.#rate;
|
||||
this.#audio = audio;
|
||||
return new Promise((resolve) => {
|
||||
let started = false;
|
||||
audio.onplaying = () => {
|
||||
@@ -146,10 +178,13 @@ export class VoiceEngine {
|
||||
}
|
||||
|
||||
#releaseAudio() {
|
||||
if (this.#audio) {
|
||||
this.#audio.onpause = null;
|
||||
this.#audio.pause?.();
|
||||
this.#audio = null;
|
||||
if (this.#player) {
|
||||
// Handlers retirés d'abord : pause() ne doit pas être pris pour une interruption à signaler.
|
||||
this.#player.onpause = null;
|
||||
this.#player.onended = null;
|
||||
this.#player.onerror = null;
|
||||
this.#player.onplaying = null;
|
||||
this.#player.pause?.();
|
||||
}
|
||||
if (this.#objectUrl) {
|
||||
URL.revokeObjectURL(this.#objectUrl);
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"settings.sound": "Sound effects",
|
||||
"settings.volume": "Volume",
|
||||
"settings.voice": "Voice",
|
||||
"voice.failed": "The voice cannot be played on this device. Check the volume and the browser's sound permission.",
|
||||
"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",
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"settings.sound": "Effets sonores",
|
||||
"settings.volume": "Volume",
|
||||
"settings.voice": "Voix",
|
||||
"voice.failed": "Impossible de lire la voix sur cet appareil. Vérifie le volume et l'autorisation du son dans le navigateur.",
|
||||
"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",
|
||||
|
||||
+13
-2
@@ -58,6 +58,7 @@ class App {
|
||||
#voice;
|
||||
#manager;
|
||||
#toast;
|
||||
#notebook;
|
||||
#map;
|
||||
#panel;
|
||||
#levelIds = [];
|
||||
@@ -83,9 +84,10 @@ class App {
|
||||
|
||||
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
|
||||
const notebook = new NotebookView(this.#i18n, {
|
||||
onSpeak: (text, step) => this.#voice.speak(text, this.#i18n.lang, { audioUrl: step.audioUrl }),
|
||||
onSpeak: (text, step) => this.#speak(text, step.audioUrl),
|
||||
canSpeak: () => this.#voice.supported && this.#voice.enabled,
|
||||
});
|
||||
this.#notebook = notebook;
|
||||
const toast = new BadgeToast(this.#i18n);
|
||||
this.#toast = toast;
|
||||
this.#manager = new CellManager({
|
||||
@@ -163,6 +165,7 @@ class App {
|
||||
this.#audio.setEnabled(settings.soundEnabled);
|
||||
this.#audio.setVolume(settings.volume);
|
||||
this.#voice.setEnabled(settings.voiceEnabled);
|
||||
this.#notebook.refreshVoiceButtons();
|
||||
this.#voice.setRate(settings.voiceRate);
|
||||
if (key === 'lang') {
|
||||
this.#i18n.setLang(value);
|
||||
@@ -186,7 +189,15 @@ class App {
|
||||
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 });
|
||||
await this.#speak(sample, audioUrl);
|
||||
}
|
||||
|
||||
/** Lit un texte ; si rien ne peut être joué, prévient l'apprenant au lieu de rester silencieux. */
|
||||
async #speak(text, audioUrl) {
|
||||
await this.#voice.speak(text, this.#i18n.lang, { audioUrl });
|
||||
if (this.#voice.lastFailure) {
|
||||
this.#toast.show(this.#i18n.t('voice.failed'));
|
||||
}
|
||||
}
|
||||
|
||||
#registerServiceWorker() {
|
||||
|
||||
@@ -54,12 +54,29 @@ export class NotebookView {
|
||||
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, step) }));
|
||||
if (voice && this.#onSpeak) {
|
||||
// Toujours rendu, affiché ou non selon le réglage (voir refreshVoiceButtons).
|
||||
children.push(
|
||||
el('button', {
|
||||
type: 'button',
|
||||
class: 'btn voice-button',
|
||||
hidden: !this.#canSpeak(),
|
||||
text: this.#i18n.t('voice.listen'),
|
||||
onclick: () => this.#onSpeak(text, step),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
|
||||
}
|
||||
|
||||
/** Réaffiche ou masque les boutons « Écouter » existants (réglage de la voix modifié). */
|
||||
refreshVoiceButtons() {
|
||||
const visible = this.#canSpeak();
|
||||
for (const button of this.#root.querySelectorAll('.voice-button')) {
|
||||
button.hidden = !visible;
|
||||
}
|
||||
}
|
||||
|
||||
/** Bouton « Continuer » ou équivalent ; retiré du DOM une fois cliqué. */
|
||||
addAction(label, onClick) {
|
||||
const button = el('button', {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// - Pyodide vendorisé, niveaux, scripts : mis en cache à la première utilisation (hors ligne ensuite).
|
||||
// Les en-têtes COOP/COEP du document viennent du serveur ; ce worker ne les fabrique pas.
|
||||
|
||||
const CACHE_VERSION = 'pyquest-v1';
|
||||
const CACHE_VERSION = 'pyquest-v2';
|
||||
|
||||
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/app.css', 'icons/icon.svg', 'js/main.js'];
|
||||
|
||||
@@ -27,10 +27,10 @@ self.addEventListener('fetch', (event) => {
|
||||
if (request.method !== 'GET' || url.origin !== self.location.origin) {
|
||||
return;
|
||||
}
|
||||
// Niveaux : réseau d'abord (contenu qui évolue), cache en repli hors ligne.
|
||||
// Le reste (code, Pyodide) : cache d'abord, rempli à la première requête.
|
||||
const networkFirst = url.pathname.startsWith('/levels/') || request.mode === 'navigate';
|
||||
event.respondWith(networkFirst ? fromNetwork(request) : fromCache(request));
|
||||
// Pyodide (versionné, immuable, lourd) : cache d'abord. Tout le reste (code, niveaux, audio) :
|
||||
// réseau d'abord, cache en repli hors ligne — jamais de code périmé servi en ligne.
|
||||
const immutable = url.pathname.startsWith('/vendor/pyodide/');
|
||||
event.respondWith(immutable ? fromCache(request) : fromNetwork(request));
|
||||
});
|
||||
|
||||
async function fromCache(request) {
|
||||
|
||||
+45
-42
@@ -146,49 +146,52 @@ 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 });
|
||||
test('narration : fichier Piper lu jusqu\'au bout (politique autoplay par défaut), réglage immédiat', { skip, timeout: 120000 }, async () => {
|
||||
// Pas d'option d'autoplay : on reproduit le comportement d'un navigateur ordinaire.
|
||||
const page = await (await browser.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', () => {
|
||||
if (this.src.startsWith('blob:')) window.__audio.ended += 1; // ignore le silence d'amorçage
|
||||
});
|
||||
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 });
|
||||
// La voix est activée par défaut : le bouton est là dès la première étape, sans rechargement.
|
||||
const listen = page.locator('.explain .voice-button').first();
|
||||
await listen.waitFor({ state: 'visible' });
|
||||
await listen.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 });
|
||||
// Désactiver la voix masque immédiatement le bouton déjà affiché ; la réactiver le ramène.
|
||||
await page.locator('#settings-toggle').click();
|
||||
const voiceSetting = page.getByLabel('Voix', { exact: true });
|
||||
await voiceSetting.uncheck();
|
||||
await listen.waitFor({ state: 'hidden' });
|
||||
await voiceSetting.check();
|
||||
await listen.waitFor({ state: 'visible' });
|
||||
|
||||
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();
|
||||
}
|
||||
// Échantillon des réglages.
|
||||
const before = await page.evaluate(() => window.__audio.ended);
|
||||
await page.locator('.settings').getByRole('button', { name: 'Tester la voix' }).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, []);
|
||||
});
|
||||
|
||||
@@ -29,8 +29,12 @@ 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(); }
|
||||
constructor() { this.src = ''; }
|
||||
play() {
|
||||
// Le silence d'amorçage (data:) ne déclenche rien ; une vraie source blob se termine seule.
|
||||
if (this.src.startsWith('blob:')) { played.push(this.src); queueMicrotask(() => { this.onplaying?.(); this.onended?.(); }); }
|
||||
return Promise.resolve();
|
||||
}
|
||||
pause() {}
|
||||
}
|
||||
const spoken2 = [];
|
||||
@@ -40,8 +44,14 @@ const fetchFn = async (url) => (url.endsWith('/there.mp3') ? { ok: true, blob: a
|
||||
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(v2.lastFailure, null);
|
||||
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
|
||||
assert.equal(v2.lastFailure, null);
|
||||
// Rien ne peut jouer (ni fichier, ni voix système) : panne signalée, pas silence.
|
||||
const v3 = new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: FakeAudio, fetchFn });
|
||||
assert.equal(await v3.speak('x', 'fr', { audioUrl: '/a/absent.mp3' }), false);
|
||||
assert.equal(v3.lastFailure, 'unavailable');
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user