"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; /** interrupted = true, wenn die Ausgabe abgebrochen oder durch eine neue ersetzt wurde. */ onEnd?: (interrupted: boolean) => void; } /** * Wartet, bis der Browser seine Stimmen geladen hat. Auf Android ist die Liste anfangs oft leer * und „voiceschanged“ kommt manchmal gar nicht – deshalb zusätzlich regelmäßig nachfragen. */ export function voicesReady(timeout = 2500): Promise { return new Promise((resolve) => { if (!ttsSupported()) return resolve([]); if (loadVoices().length) return resolve(voicesCache); let done = false; const finish = () => { if (done) return; done = true; clearInterval(poll); resolve(loadVoices()); }; const poll = setInterval(() => loadVoices().length && finish(), 200); window.speechSynthesis.addEventListener("voiceschanged", finish, { once: true }); setTimeout(finish, timeout); }); } export function hasGermanVoice(): boolean { return germanVoices().length > 0; } /** * true nur, wenn das Gerät Stimmen meldet, aber keine deutsche dabei ist. * Eine (noch) leere Liste zählt NICHT als fehlend – Android liefert die Liste oft verspätet, * spricht mit lang="de-DE" aber trotzdem Deutsch. */ export function germanVoiceMissing(): boolean { return loadVoices().length > 0 && 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"; // Laufende Äußerungen festhalten: Chrome räumt sie sonst manchmal per Garbage Collection weg, // dann kommt nie ein „onend“ und Dialoge bleiben nach der ersten Zeile hängen. const alive = new Set(); // Jede neue Ausgabe bekommt eine Nummer; ältere Rückmeldungen werden dadurch erkannt. let generation = 0; const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** Einmal bei der ersten Berührung aufrufen: „entsperrt“ die Sprachausgabe auf Mobilgeräten. */ export function primeSpeech() { if (!ttsSupported()) return; try { const u = new SpeechSynthesisUtterance(" "); u.volume = 0; u.lang = "de-DE"; window.speechSynthesis.speak(u); } catch { /* ignorieren */ } loadVoices(); } /** Spricht einen Text. Eine laufende Ausgabe wird dabei sauber beendet. */ export function speak(text: string, opts: SpeakOptions = {}): void { if (!ttsSupported() || !text.trim()) { opts.onEnd?.(true); return; } const my = ++generation; const synth = window.speechSynthesis; const busy = synth.speaking || synth.pending; if (busy) synth.cancel(); void voicesReady() // Direkt nach cancel() verschluckt Chrome neue Äußerungen oft – kurz warten. .then(() => delay(busy ? 180 : 0)) .then(() => { if (my !== generation) return opts.onEnd?.(true); speakNow(text, opts, my); }); } function speakNow(text: string, opts: SpeakOptions, my: number) { const synth = window.speechSynthesis; const v = pickVoice(opts.gender ?? "f", opts.voiceIndex ?? 0); // Nie Deutsch mit einer englischen Stimme vorlesen – stattdessen Hinweis anzeigen. if (!v && germanVoiceMissing()) { window.dispatchEvent(new Event(TTS_MISSING_EVENT)); opts.onEnd?.(true); return; } // Ohne passende männliche Stimme (z. B. Android hat oft nur eine deutsche Stimme): tiefere Tonlage const hasGendered = v ? (opts.gender === "m" ? maleHints : femaleHints).some((h) => v.name.toLowerCase().includes(h)) : false; const pitch = !hasGendered && opts.gender === "m" ? 0.75 : 1; const lang = v ? v.lang.replace("_", "-") : "de-DE"; const rate = opts.rate ?? 0.95; // Lange Texte satzweise sprechen: manche Engines brechen lange Äußerungen sonst ab. const chunks = splitSentences(text); let finished = false; let started = false; let retried = false; let utterances: SpeechSynthesisUtterance[] = []; const timers: ReturnType[] = []; let poll: ReturnType | undefined; const finish = (interrupted: boolean) => { if (finished) return; finished = true; timers.forEach(clearTimeout); if (poll) clearInterval(poll); utterances.forEach((u) => alive.delete(u)); opts.onEnd?.(interrupted || my !== generation); }; const run = () => { utterances = chunks.map((chunk, i) => { const u = new SpeechSynthesisUtterance(chunk); if (v) u.voice = v; u.lang = lang; u.rate = rate; u.pitch = pitch; u.onstart = () => { started = true; }; u.onerror = (e) => { if (e.error === "interrupted" || e.error === "canceled") return finish(true); // Anderer Fehler (z. B. Engine hängt): einmal neu versuchen if (!retried && my === generation) return retry(); finish(false); }; if (i === chunks.length - 1) u.onend = () => finish(false); alive.add(u); return u; }); // Android pausiert die Sprachausgabe manchmal, wenn die App im Hintergrund war. synth.resume(); utterances.forEach((u) => synth.speak(u)); }; const retry = () => { retried = true; // Eigene Handler lösen, sonst würde das cancel() als „unterbrochen“ gewertet utterances.forEach((u) => { u.onstart = null; u.onend = null; u.onerror = null; alive.delete(u); }); synth.cancel(); timers.push( setTimeout(() => { if (my !== generation || finished) return; run(); }, 250), ); }; run(); // Wachhund 1: Startet die Ausgabe nicht, Engine zurücksetzen und noch einmal versuchen. timers.push( setTimeout(() => { if (finished || started || my !== generation) return; if (!retried) retry(); else finish(false); }, 2500), ); // Wachhund 2: Manche Android-Versionen melden das Ende nie – dann selbst erkennen. poll = setInterval(() => { if (my !== generation) return finish(true); if (started && !synth.speaking && !synth.pending) finish(false); }, 400); // Wachhund 3: Obergrenze, damit nichts ewig hängt. timers.push(setTimeout(() => finish(false), (text.length * 110) / rate + 10000)); } 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) { stopped = true; onDone(); return; } onLine(i); const it = items[i++]; speak(it.text, { rate, gender: it.gender, voiceIndex: it.voiceIndex, onEnd: (interrupted) => { if (stopped) return; // Von außen unterbrochen (z. B. anderer Vorlese-Knopf): Dialog beenden statt weiterzuspringen if (interrupted) { stopped = true; onDone(); return; } setTimeout(next, 350); }, }); }; next(); return () => { stopped = true; stopSpeaking(); }; } export function stopSpeaking() { if (!ttsSupported()) return; generation++; window.speechSynthesis.cancel(); } // ---------- Spracherkennung ---------- type RecognitionCtor = new () => { lang: string; interimResults: boolean; continuous: boolean; start: () => void; stop: () => void; onresult: ((e: { results: ArrayLike & { 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(); }