Files
chadiapp/lib/speech.ts
T
X4Lo 1f1d28a34d Add B1 Meister: OeSD B1 exam trainer (German-Arabic)
Next.js app with Hoeren, Lesen, Schreiben, Sprechen, Grammatik and Wortschatz sections, flashcards with spaced repetition, speaking chat, XP/streaks/badges, daily reminders (PWA) and Docker Compose setup for Coolify.
2026-11-05 19:11:46 +00:00

214 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
// Text-to-Speech (Hören) und Spracherkennung (Sprechen) über die Web Speech API.
let voicesCache: SpeechSynthesisVoice[] = [];
function loadVoices(): SpeechSynthesisVoice[] {
if (typeof window === "undefined" || !("speechSynthesis" in window)) return [];
const v = window.speechSynthesis.getVoices();
if (v.length) voicesCache = v;
return voicesCache;
}
if (typeof window !== "undefined" && "speechSynthesis" in window) {
loadVoices();
window.speechSynthesis.onvoiceschanged = () => loadVoices();
}
export function ttsSupported(): boolean {
return typeof window !== "undefined" && "speechSynthesis" in window;
}
const femaleHints = ["female", "frau", "katja", "hedda", "anna", "petra", "marlene", "vicki", "helena", "ingrid", "seraphina", "amala", "elke", "gisela", "klarissa", "louisa", "maja", "tanja", "google deutsch"];
const maleHints = ["male", "stefan", "conrad", "hans", "markus", "yannick", "florian", "killian", "jonas", "christoph", "ralf", "bernd", "kasper", "michael"];
export function germanVoices(): SpeechSynthesisVoice[] {
const all = loadVoices();
const de = all.filter((v) => v.lang.toLowerCase().startsWith("de"));
// de-AT zuerst (ÖSD ist österreichisch), dann Online-/Natural-Stimmen
return de.sort((a, b) => score(b) - score(a));
function score(v: SpeechSynthesisVoice) {
let s = 0;
if (v.lang.toLowerCase() === "de-at") s += 3;
if (/natural|online|neural|premium|enhanced/i.test(v.name)) s += 2;
return s;
}
}
function pickVoice(gender: "f" | "m", index = 0): SpeechSynthesisVoice | undefined {
const voices = germanVoices();
if (!voices.length) return undefined;
const hints = gender === "f" ? femaleHints : maleHints;
const matching = voices.filter((v) => hints.some((h) => v.name.toLowerCase().includes(h)));
const list = matching.length ? matching : voices;
return list[index % list.length];
}
export interface SpeakOptions {
rate?: number;
gender?: "f" | "m";
voiceIndex?: number;
onEnd?: () => void;
}
/** Wartet kurz, bis der Browser seine Stimmen geladen hat (die Liste ist anfangs oft leer). */
export function voicesReady(timeout = 1500): Promise<SpeechSynthesisVoice[]> {
return new Promise((resolve) => {
if (!ttsSupported()) return resolve([]);
if (loadVoices().length) return resolve(voicesCache);
const done = () => resolve(loadVoices());
window.speechSynthesis.addEventListener("voiceschanged", done, { once: true });
setTimeout(done, timeout);
});
}
export function hasGermanVoice(): boolean {
return germanVoices().length > 0;
}
/** Wird ausgelöst, wenn keine deutsche Stimme vorhanden ist (AppShell zeigt dann eine Anleitung). */
export const TTS_MISSING_EVENT = "b1meister:tts-missing";
export function speak(text: string, opts: SpeakOptions = {}): void {
if (!ttsSupported()) {
opts.onEnd?.();
return;
}
void voicesReady().then(() => speakNow(text, opts));
}
function speakNow(text: string, opts: SpeakOptions) {
const v = pickVoice(opts.gender ?? "f", opts.voiceIndex ?? 0);
// Nie Deutsch mit einer englischen Stimme vorlesen – stattdessen Hinweis anzeigen.
if (!v) {
window.dispatchEvent(new Event(TTS_MISSING_EVENT));
opts.onEnd?.();
return;
}
// Ohne passende männliche Stimme (z. B. Android hat oft nur eine deutsche Stimme): tiefere Tonlage
const hasGendered = (opts.gender === "m" ? maleHints : femaleHints).some((h) => v.name.toLowerCase().includes(h));
const pitch = !hasGendered && opts.gender === "m" ? 0.75 : 1;
// Lange Texte satzweise sprechen: manche Engines (Android, Chrome-Onlinestimmen) brechen lange Äußerungen sonst ab.
const chunks = splitSentences(text);
chunks.forEach((chunk, i) => {
const u = new SpeechSynthesisUtterance(chunk);
u.voice = v;
u.lang = v.lang;
u.rate = opts.rate ?? 0.95;
u.pitch = pitch;
if (i === chunks.length - 1) {
u.onend = () => opts.onEnd?.();
u.onerror = () => opts.onEnd?.();
}
window.speechSynthesis.speak(u);
});
}
function splitSentences(text: string): string[] {
const parts = text
.replace(/\s+/g, " ")
.split(/(?<=[.!?…:])\s+(?=[„"A-ZÄÖÜ0-9])/)
.map((s) => s.trim())
.filter(Boolean);
// Sehr kurze Stücke zusammenfassen, damit es natürlich klingt
const out: string[] = [];
for (const p of parts) {
if (out.length && (out[out.length - 1].length < 40 || p.length < 15) && out[out.length - 1].length + p.length < 220) out[out.length - 1] += " " + p;
else out.push(p);
}
return out.length ? out : [text];
}
/** Mehrere Zeilen nacheinander sprechen. Gibt eine Stopp-Funktion zurück. */
export function speakSequence(
items: { text: string; gender: "f" | "m"; voiceIndex?: number }[],
rate: number,
onLine: (i: number) => void,
onDone: () => void,
): () => void {
let stopped = false;
let i = 0;
const next = () => {
if (stopped) return;
if (i >= items.length) {
onDone();
return;
}
onLine(i);
const it = items[i++];
speak(it.text, { rate, gender: it.gender, voiceIndex: it.voiceIndex, onEnd: () => setTimeout(next, 350) });
};
stopSpeaking();
void voicesReady().then(() => {
if (stopped) return;
if (!hasGermanVoice()) {
window.dispatchEvent(new Event(TTS_MISSING_EVENT));
onDone();
return;
}
next();
});
return () => {
stopped = true;
stopSpeaking();
};
}
export function stopSpeaking() {
if (ttsSupported()) window.speechSynthesis.cancel();
}
// ---------- Spracherkennung ----------
type RecognitionCtor = new () => {
lang: string;
interimResults: boolean;
continuous: boolean;
start: () => void;
stop: () => void;
onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }> & { isFinal: boolean }> }) => void) | null;
onend: (() => void) | null;
onerror: ((e: { error: string }) => void) | null;
};
export function sttSupported(): boolean {
if (typeof window === "undefined") return false;
const w = window as unknown as { SpeechRecognition?: RecognitionCtor; webkitSpeechRecognition?: RecognitionCtor };
return Boolean(w.SpeechRecognition || w.webkitSpeechRecognition);
}
export function startListening(
onText: (text: string, final: boolean) => void,
onEnd: (error?: string) => void,
): (() => void) | null {
const w = window as unknown as { SpeechRecognition?: RecognitionCtor; webkitSpeechRecognition?: RecognitionCtor };
const Ctor = w.SpeechRecognition || w.webkitSpeechRecognition;
if (!Ctor) return null;
const rec = new Ctor();
rec.lang = "de-AT";
rec.interimResults = true;
rec.continuous = true;
let finalText = "";
rec.onresult = (e) => {
let interim = "";
finalText = "";
for (let i = 0; i < e.results.length; i++) {
const r = e.results[i];
if (r.isFinal) finalText += r[0].transcript + " ";
else interim += r[0].transcript;
}
onText((finalText + interim).trim(), interim === "");
};
let err: string | undefined;
rec.onerror = (e) => {
err = e.error;
};
rec.onend = () => onEnd(err);
try {
rec.start();
} catch {
return null;
}
return () => rec.stop();
}