Files
X4Lo 5d760c0bf6 Make text-to-speech reliable on Android
Do not treat a not-yet-loaded voice list as missing German voice, poll for voices, wait after cancel before speaking, keep utterances referenced, retry stalled speech, detect missing end events, unlock speech on first tap, and stop the microphone before the examiner speaks.
2026-11-06 22:17:32 +00:00

190 lines
6.9 KiB
TypeScript
Raw Permalink 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";
import { useEffect, useMemo, useRef, useState } from "react";
import { hoerItems, hoerTeile, type HoerItem } from "@/data/hoeren";
import Quiz from "@/components/Quiz";
import ResultCard from "@/components/ResultCard";
import Ar from "@/components/Ar";
import { recordResult, useProgress } from "@/lib/progress";
import { germanVoiceMissing, speakSequence, stopSpeaking, TTS_MISSING_EVENT, ttsSupported } from "@/lib/speech";
export default function HoerenPage() {
const [teil, setTeil] = useState<number>(1);
const [item, setItem] = useState<HoerItem | null>(null);
const p = useProgress();
const list = hoerItems.filter((h) => h.teil === teil);
const info = hoerTeile.find((t) => t.teil === teil)!;
if (item) return <Player key={item.id} item={item} onBack={() => setItem(null)} />;
return (
<div>
<h1>🎧 Hören</h1>
<p className="sub">
Hör genau zu und beantworte die Fragen. <Ar>استمع جيداً وأجب عن الأسئلة.</Ar>
</p>
<div className="tabs">
{hoerTeile.map((t) => (
<button key={t.teil} className={teil === t.teil ? "active" : ""} onClick={() => setTeil(t.teil)}>
Teil {t.teil}
</button>
))}
</div>
<div className="card" style={{ background: "var(--blue-soft)", borderColor: "var(--blue)" }}>
<h3>{info.de}</h3>
<div className="ar">{info.ar}</div>
<div className="small" style={{ marginTop: 4 }}>
💡 {info.hint}
</div>
</div>
<div className="grid" style={{ marginTop: 12 }}>
{list.map((h) => {
const score = p.done[h.id];
return (
<button key={h.id} className="tile" onClick={() => setItem(h)}>
<div className="row">
<span style={{ fontSize: 28 }}>{h.lines.length > 1 ? "💬" : "📻"}</span>
<div style={{ flex: 1 }}>
<div className="t" style={{ marginTop: 0 }}>
{h.title}
</div>
<div className="s ar" style={{ textAlign: "left" }}>
{h.titleAr}
</div>
</div>
{score !== undefined ? <span className={`pill ${score >= 60 ? "green" : "yellow"}`}>{score} %</span> : <span className="pill">{h.questions.length} Fragen</span>}
</div>
</button>
);
})}
</div>
</div>
);
}
function Player({ item, onBack }: { item: HoerItem; onBack: () => void }) {
const [rate, setRate] = useState(0.95);
const [playing, setPlaying] = useState(false);
const [line, setLine] = useState(-1);
const [plays, setPlays] = useState(0);
const [exam, setExam] = useState(false);
const [result, setResult] = useState<{ c: number; t: number; xp: number } | null>(null);
const [round, setRound] = useState(0);
const stopRef = useRef<(() => void) | null>(null);
const maxPlays = item.teil === 1 || item.teil === 4 ? 2 : 1;
const voices = useMemo(() => {
const counters = { f: 0, m: 0 };
const map: Record<string, { gender: "f" | "m"; idx: number }> = {};
Object.entries(item.speakers).forEach(([name, g]) => {
map[name] = { gender: g, idx: counters[g]++ };
});
return map;
}, [item]);
useEffect(() => () => stopSpeaking(), []);
const play = () => {
if (playing) {
stopRef.current?.();
setPlaying(false);
setLine(-1);
return;
}
if (exam && plays >= maxPlays) return;
if (germanVoiceMissing()) {
window.dispatchEvent(new Event(TTS_MISSING_EVENT));
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
setPlaying(true);
setPlays((n) => n + 1);
stopRef.current = speakSequence(
item.lines.map((l) => ({ text: l.t, gender: voices[l.who]?.gender ?? "f", voiceIndex: voices[l.who]?.idx ?? 0 })),
rate,
(i) => setLine(i),
() => {
setPlaying(false);
setLine(-1);
},
);
};
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>{item.title}</h1>
<div className="ar muted">{item.titleAr}</div>
<div className="card" style={{ marginTop: 12 }}>
<div className="pill">Teil {item.teil}</div>
<p style={{ fontWeight: 700 }}>{item.situation}</p>
<Ar block>{item.situationAr}</Ar>
{!ttsSupported() && <div className="feedback no">Dein Browser unterstützt keine Sprachausgabe. Bitte Chrome, Edge oder Safari verwenden.</div>}
<div className="row" style={{ marginTop: 14 }}>
<button className={`btn ${playing ? "secondary" : "blue"}`} onClick={play} disabled={!playing && exam && plays >= maxPlays}>
{playing ? "⏹ Stopp" : plays === 0 ? "▶ Abspielen" : "🔁 Nochmal hören"}
</button>
<select value={rate} onChange={(e) => setRate(Number(e.target.value))} style={{ width: "auto" }} aria-label="Geschwindigkeit">
<option value={0.75}>🐢 Langsam</option>
<option value={0.95}>🚶 Normal</option>
<option value={1.1}>🐇 Schnell</option>
</select>
<label className="row small" style={{ gap: 6 }}>
<input type="checkbox" checked={exam} onChange={(e) => setExam(e.target.checked)} style={{ width: 18, height: 18 }} />
Prüfungsmodus ({maxPlays}× hören)
</label>
</div>
<div className="small muted" style={{ marginTop: 8 }}>
{playing && line >= 0 ? `🔊 ${item.lines[line].who} spricht …` : `Gehört: ${plays}×`}
</div>
</div>
<h2>Fragen • الأسئلة</h2>
<Quiz
key={round}
questions={item.questions}
onFinish={(c, t) => {
const xp = 5 + c * 3;
recordResult(item.id, "hoeren", (c / t) * 100, xp);
setResult({ c, t, xp });
}}
/>
{result && (
<>
<ResultCard
correct={result.c}
total={result.t}
xp={result.xp}
onRetry={() => {
setResult(null);
setRound((r) => r + 1);
setPlays(0);
}}
/>
<h2>Transkript • النص</h2>
<div className="card">
{item.lines.map((l, i) => (
<p key={i} style={{ margin: "0 0 10px", background: line === i ? "var(--yellow-soft)" : undefined, borderRadius: 8 }}>
{item.lines.length > 1 || item.teil !== 1 ? <b>{l.who}: </b> : null}
{l.t}
</p>
))}
<details style={{ marginTop: 10 }}>
<summary>🌍 Arabische Übersetzung • الترجمة العربية</summary>
<div className="ar" style={{ marginTop: 8 }}>
{item.translationAr}
</div>
</details>
</div>
</>
)}
</div>
);
}