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.
|
`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) ;
|
- **À 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`
|
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**
|
dans `scripts/generate_voice.py`) selon son retour. La voix est **activée par défaut**
|
||||||
(réglage « Voix ») : à reconsidérer. Piper = GPL-3.0 mais outil de build seulement.
|
(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
|
- 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()`).
|
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
|
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)
|
## 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
|
- 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
|
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).
|
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'
|
theme: 'auto', // 'auto' | 'light' | 'dark'
|
||||||
soundEnabled: true,
|
soundEnabled: true,
|
||||||
volume: 0.8,
|
volume: 0.8,
|
||||||
voiceEnabled: false,
|
voiceEnabled: true, // le bouton « Écouter » ne lit jamais automatiquement : un clic à chaque fois
|
||||||
voiceRate: 1,
|
voiceRate: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+46
-11
@@ -4,6 +4,8 @@
|
|||||||
// Aucun service tiers.
|
// Aucun service tiers.
|
||||||
|
|
||||||
const LANG_TAGS = { fr: 'fr-FR', en: 'en-US' };
|
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 {
|
export class VoiceEngine {
|
||||||
#synth;
|
#synth;
|
||||||
@@ -12,9 +14,10 @@ export class VoiceEngine {
|
|||||||
#fetch;
|
#fetch;
|
||||||
#enabled;
|
#enabled;
|
||||||
#rate;
|
#rate;
|
||||||
#audio = null;
|
#player = null;
|
||||||
#objectUrl = null;
|
#objectUrl = null;
|
||||||
#session = 0;
|
#session = 0;
|
||||||
|
#lastFailure = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {object} [options]
|
* @param {object} [options]
|
||||||
@@ -54,6 +57,11 @@ export class VoiceEngine {
|
|||||||
return this.#rate;
|
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) {
|
setEnabled(enabled) {
|
||||||
this.#enabled = enabled;
|
this.#enabled = enabled;
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
@@ -63,8 +71,8 @@ export class VoiceEngine {
|
|||||||
|
|
||||||
setRate(rate) {
|
setRate(rate) {
|
||||||
this.#rate = Math.min(2, Math.max(0.5, rate));
|
this.#rate = Math.min(2, Math.max(0.5, rate));
|
||||||
if (this.#audio) {
|
if (this.#player) {
|
||||||
this.#audio.playbackRate = this.#rate;
|
this.#player.playbackRate = this.#rate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,21 +85,45 @@ export class VoiceEngine {
|
|||||||
* @returns {Promise<boolean>}
|
* @returns {Promise<boolean>}
|
||||||
*/
|
*/
|
||||||
async speak(text, lang = 'fr', { audioUrl = null } = {}) {
|
async speak(text, lang = 'fr', { audioUrl = null } = {}) {
|
||||||
|
this.#lastFailure = null;
|
||||||
if (!this.supported || !this.#enabled) {
|
if (!this.supported || !this.#enabled) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
this.cancel();
|
this.cancel();
|
||||||
|
// Doit s'exécuter de façon synchrone dans le gestionnaire de clic, avant tout await.
|
||||||
|
this.#prime();
|
||||||
const session = this.#session;
|
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) {
|
if (audioUrl && this.#AudioClass) {
|
||||||
const played = await this.#playFile(audioUrl, session);
|
const played = await this.#playFile(audioUrl, session);
|
||||||
if (played !== null) {
|
if (played !== null) {
|
||||||
return played;
|
return finish(played);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (session !== this.#session) {
|
if (session !== this.#session) {
|
||||||
return false;
|
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). */
|
/** 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).
|
// Lecture depuis un blob : pas de requêtes Range (exigées par iOS pour un flux direct).
|
||||||
this.#objectUrl = URL.createObjectURL(blob);
|
this.#objectUrl = URL.createObjectURL(blob);
|
||||||
const audio = new this.#AudioClass(this.#objectUrl);
|
const audio = this.#player;
|
||||||
|
audio.src = this.#objectUrl;
|
||||||
audio.playbackRate = this.#rate;
|
audio.playbackRate = this.#rate;
|
||||||
this.#audio = audio;
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
let started = false;
|
let started = false;
|
||||||
audio.onplaying = () => {
|
audio.onplaying = () => {
|
||||||
@@ -146,10 +178,13 @@ export class VoiceEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#releaseAudio() {
|
#releaseAudio() {
|
||||||
if (this.#audio) {
|
if (this.#player) {
|
||||||
this.#audio.onpause = null;
|
// Handlers retirés d'abord : pause() ne doit pas être pris pour une interruption à signaler.
|
||||||
this.#audio.pause?.();
|
this.#player.onpause = null;
|
||||||
this.#audio = null;
|
this.#player.onended = null;
|
||||||
|
this.#player.onerror = null;
|
||||||
|
this.#player.onplaying = null;
|
||||||
|
this.#player.pause?.();
|
||||||
}
|
}
|
||||||
if (this.#objectUrl) {
|
if (this.#objectUrl) {
|
||||||
URL.revokeObjectURL(this.#objectUrl);
|
URL.revokeObjectURL(this.#objectUrl);
|
||||||
|
|||||||
@@ -59,6 +59,7 @@
|
|||||||
"settings.sound": "Sound effects",
|
"settings.sound": "Sound effects",
|
||||||
"settings.volume": "Volume",
|
"settings.volume": "Volume",
|
||||||
"settings.voice": "Voice",
|
"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.",
|
"voice.sample": "Hello, I am the voice of PyQuest. This is how I will read the explanations.",
|
||||||
"settings.testSound": "Test the sound",
|
"settings.testSound": "Test the sound",
|
||||||
"settings.testVoice": "Test the voice",
|
"settings.testVoice": "Test the voice",
|
||||||
|
|||||||
@@ -59,6 +59,7 @@
|
|||||||
"settings.sound": "Effets sonores",
|
"settings.sound": "Effets sonores",
|
||||||
"settings.volume": "Volume",
|
"settings.volume": "Volume",
|
||||||
"settings.voice": "Voix",
|
"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.",
|
"voice.sample": "Bonjour, je suis la voix de PyQuest. Voici comment je lirai les explications.",
|
||||||
"settings.testSound": "Tester le son",
|
"settings.testSound": "Tester le son",
|
||||||
"settings.testVoice": "Tester la voix",
|
"settings.testVoice": "Tester la voix",
|
||||||
|
|||||||
+13
-2
@@ -58,6 +58,7 @@ class App {
|
|||||||
#voice;
|
#voice;
|
||||||
#manager;
|
#manager;
|
||||||
#toast;
|
#toast;
|
||||||
|
#notebook;
|
||||||
#map;
|
#map;
|
||||||
#panel;
|
#panel;
|
||||||
#levelIds = [];
|
#levelIds = [];
|
||||||
@@ -83,9 +84,10 @@ class App {
|
|||||||
|
|
||||||
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
|
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
|
||||||
const notebook = new NotebookView(this.#i18n, {
|
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,
|
canSpeak: () => this.#voice.supported && this.#voice.enabled,
|
||||||
});
|
});
|
||||||
|
this.#notebook = notebook;
|
||||||
const toast = new BadgeToast(this.#i18n);
|
const toast = new BadgeToast(this.#i18n);
|
||||||
this.#toast = toast;
|
this.#toast = toast;
|
||||||
this.#manager = new CellManager({
|
this.#manager = new CellManager({
|
||||||
@@ -163,6 +165,7 @@ class App {
|
|||||||
this.#audio.setEnabled(settings.soundEnabled);
|
this.#audio.setEnabled(settings.soundEnabled);
|
||||||
this.#audio.setVolume(settings.volume);
|
this.#audio.setVolume(settings.volume);
|
||||||
this.#voice.setEnabled(settings.voiceEnabled);
|
this.#voice.setEnabled(settings.voiceEnabled);
|
||||||
|
this.#notebook.refreshVoiceButtons();
|
||||||
this.#voice.setRate(settings.voiceRate);
|
this.#voice.setRate(settings.voiceRate);
|
||||||
if (key === 'lang') {
|
if (key === 'lang') {
|
||||||
this.#i18n.setLang(value);
|
this.#i18n.setLang(value);
|
||||||
@@ -186,7 +189,15 @@ class App {
|
|||||||
const lang = this.#i18n.lang;
|
const lang = this.#i18n.lang;
|
||||||
const sample = this.#i18n.t('voice.sample');
|
const sample = this.#i18n.t('voice.sample');
|
||||||
const audioUrl = new URL(`assets/voice/${lang}/${speechKey(lang, sample)}.mp3`, document.baseURI).href;
|
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() {
|
#registerServiceWorker() {
|
||||||
|
|||||||
@@ -54,12 +54,29 @@ export class NotebookView {
|
|||||||
if (image) {
|
if (image) {
|
||||||
children.push(el('img', { src: image, alt: '' }));
|
children.push(el('img', { src: image, alt: '' }));
|
||||||
}
|
}
|
||||||
if (voice && this.#onSpeak && this.#canSpeak()) {
|
if (voice && this.#onSpeak) {
|
||||||
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text, step) }));
|
// 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));
|
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é. */
|
/** Bouton « Continuer » ou équivalent ; retiré du DOM une fois cliqué. */
|
||||||
addAction(label, onClick) {
|
addAction(label, onClick) {
|
||||||
const button = el('button', {
|
const button = el('button', {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// - Pyodide vendorisé, niveaux, scripts : mis en cache à la première utilisation (hors ligne ensuite).
|
// - 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.
|
// 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'];
|
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) {
|
if (request.method !== 'GET' || url.origin !== self.location.origin) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Niveaux : réseau d'abord (contenu qui évolue), cache en repli hors ligne.
|
// Pyodide (versionné, immuable, lourd) : cache d'abord. Tout le reste (code, niveaux, audio) :
|
||||||
// Le reste (code, Pyodide) : cache d'abord, rempli à la première requête.
|
// réseau d'abord, cache en repli hors ligne — jamais de code périmé servi en ligne.
|
||||||
const networkFirst = url.pathname.startsWith('/levels/') || request.mode === 'navigate';
|
const immutable = url.pathname.startsWith('/vendor/pyodide/');
|
||||||
event.respondWith(networkFirst ? fromNetwork(request) : fromCache(request));
|
event.respondWith(immutable ? fromCache(request) : fromNetwork(request));
|
||||||
});
|
});
|
||||||
|
|
||||||
async function fromCache(request) {
|
async function fromCache(request) {
|
||||||
|
|||||||
+20
-17
@@ -146,10 +146,9 @@ test('niveau 03 : saisie interactive et validation par rejeu scripté', { skip,
|
|||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('narration : fichier Piper lu jusqu\'au bout, échantillon des réglages, repli', { skip, timeout: 120000 }, async () => {
|
test('narration : fichier Piper lu jusqu\'au bout (politique autoplay par défaut), réglage immédiat', { skip, timeout: 120000 }, async () => {
|
||||||
const browser2 = await chromium.launch({ executablePath, args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] });
|
// Pas d'option d'autoplay : on reproduit le comportement d'un navigateur ordinaire.
|
||||||
try {
|
const page = await (await browser.newContext()).newPage();
|
||||||
const page = await (await browser2.newContext()).newPage();
|
|
||||||
const errors = [];
|
const errors = [];
|
||||||
page.on('pageerror', (error) => errors.push(error.message));
|
page.on('pageerror', (error) => errors.push(error.message));
|
||||||
const served = [];
|
const served = [];
|
||||||
@@ -163,7 +162,9 @@ test('narration : fichier Piper lu jusqu\'au bout, échantillon des réglages, r
|
|||||||
window.Audio = class extends Original {
|
window.Audio = class extends Original {
|
||||||
constructor(...args) {
|
constructor(...args) {
|
||||||
super(...args);
|
super(...args);
|
||||||
this.addEventListener('ended', () => (window.__audio.ended += 1));
|
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));
|
this.addEventListener('error', () => (window.__audio.errors += 1));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -171,24 +172,26 @@ test('narration : fichier Piper lu jusqu\'au bout, échantillon des réglages, r
|
|||||||
await page.goto(base);
|
await page.goto(base);
|
||||||
await page.waitForSelector('.explain', { timeout: 60000 });
|
await page.waitForSelector('.explain', { timeout: 60000 });
|
||||||
|
|
||||||
// La voix est désactivée par défaut : pas de bouton « Écouter ».
|
// La voix est activée par défaut : le bouton est là dès la première étape, sans rechargement.
|
||||||
assert.equal(await page.locator('.explain button', { hasText: 'Écouter' }).count(), 0);
|
const listen = page.locator('.explain .voice-button').first();
|
||||||
await page.locator('#settings-toggle').click();
|
await listen.waitFor({ state: 'visible' });
|
||||||
await page.getByLabel('Voix', { exact: true }).check();
|
await listen.click();
|
||||||
await page.locator('.settings').getByRole('button', { name: 'Tester la voix' }).click();
|
|
||||||
await page.waitForFunction(() => window.__audio.ended >= 1, null, { timeout: 30000 });
|
await page.waitForFunction(() => window.__audio.ended >= 1, null, { timeout: 30000 });
|
||||||
|
|
||||||
// Narration d'une étape de niveau : relance le niveau pour afficher le bouton.
|
// Désactiver la voix masque immédiatement le bouton déjà affiché ; la réactiver le ramène.
|
||||||
await page.locator('.level-button', { hasText: 'Ton premier programme' }).click();
|
await page.locator('#settings-toggle').click();
|
||||||
await page.waitForSelector('.explain button');
|
const voiceSetting = page.getByLabel('Voix', { exact: true });
|
||||||
|
await voiceSetting.uncheck();
|
||||||
|
await listen.waitFor({ state: 'hidden' });
|
||||||
|
await voiceSetting.check();
|
||||||
|
await listen.waitFor({ state: 'visible' });
|
||||||
|
|
||||||
|
// Échantillon des réglages.
|
||||||
const before = await page.evaluate(() => window.__audio.ended);
|
const before = await page.evaluate(() => window.__audio.ended);
|
||||||
await page.locator('.explain button', { hasText: 'Écouter' }).click();
|
await page.locator('.settings').getByRole('button', { name: 'Tester la voix' }).click();
|
||||||
await page.waitForFunction((count) => window.__audio.ended > count, before, { timeout: 30000 });
|
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.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.equal(await page.evaluate(() => window.__audio.errors), 0);
|
||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
} finally {
|
|
||||||
await browser2.close();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,8 +29,12 @@ globalThis.URL.createObjectURL = () => 'blob:fake';
|
|||||||
globalThis.URL.revokeObjectURL = () => {};
|
globalThis.URL.revokeObjectURL = () => {};
|
||||||
const played = [];
|
const played = [];
|
||||||
class FakeAudio {
|
class FakeAudio {
|
||||||
constructor(src) { this.src = src; played.push(this); }
|
constructor() { this.src = ''; }
|
||||||
play() { queueMicrotask(() => { this.onplaying?.(); this.onended?.(); }); return Promise.resolve(); }
|
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() {}
|
pause() {}
|
||||||
}
|
}
|
||||||
const spoken2 = [];
|
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 });
|
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(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(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(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(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);
|
v2.setRate(1.5); assert.equal(v2.rate, 1.5);
|
||||||
const noAudioNoSynth = new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined });
|
const noAudioNoSynth = new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined });
|
||||||
assert.equal(noAudioNoSynth.supported, false);
|
assert.equal(noAudioNoSynth.supported, false);
|
||||||
|
|||||||
Reference in New Issue
Block a user