feat(audio): add offline local neural voice via Piper (sv + en)

Announcements can use Piper, a free local neural TTS, instead of the browser's system
voice. No account, no paid service, and it keeps working with no internet at the track.

- npm run tts:install (or Settings -> Audio -> Install) downloads the standalone Piper
  release for Linux/Windows/macOS plus Swedish and English voices into piper/ once
- server/tts.js generates each line once, one at a time, and caches it as WAV under
  data/tts/; a new line takes ~0.3 s with the standalone build
- src/piper_speech.js plays it and falls back to the browser voice if Piper is missing,
  errors, or takes over 2.5 s, so no announcement is lost and timing is never held up
- "Pre-generate phrases and driver names" renders every fixed phrase and name in both
  languages before race day

Browser voice stays the default. Generation routes fall under the admin PIN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
larssandandClaude Opus 5.5 committed 2026-09-27 19:28:15 +02:00
1 parent 9016ce02e4
commit e8a2799a92
25 files changed
+776 -19

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
// "Voice engine" panel in Settings -> Audio: choose browser voices or the local Piper
// voices, install Piper + Swedish/English voices once, and pre-generate fixed phrases and
// driver names so race day never waits on generation.
const LANGUAGES = ["sv", "en"];
// Fixed per language on purpose - the sample must be in the voice being tested, not the UI language.
const SAMPLES = { sv: "Heat ett startar om tio sekunder. Nytt varvrekord för Alex Karlsson.", en: "Heat one starts in ten seconds. New lap record for Alex Karlsson." };
async function getStatus() {
return fetch("/api/tts/status").then((res) => res.json()).catch(() => null);
}
async function buildPregenerateItems(state) {
const manifest = await fetch("/race-sounds/sound_manifest.json").then((res) => res.json()).catch(() => ({}));
const items = [];
LANGUAGES.forEach((language) => {
Object.values(manifest?.voice_events?.[language] || {})
.filter((text) => typeof text === "string" && text && !text.includes("{"))
.forEach((text) => items.push({ text, language }));
(state.drivers || []).forEach((driver) => {
const name = String(driver.speechName || driver.name || "").trim();
if (name) items.push({ text: name, language });
});
});
return items;
}
export async function mountTtsSettings(container, deps) {
if (!container) return;
const { state, t, escapeHtml, saveState, speakText } = deps;
const status = await getStatus();
if (!container.isConnected) return;
const remount = () => mountTtsSettings(container, deps);
const hasLanguage = (language) => Boolean(status?.voices?.some((voice) => voice.language === language));
const engine = state.settings.ttsEngine === "piper" ? "piper" : "browser";
const install = status?.install || {};
const pregen = status?.pregenerate || {};
const busy = install.running || pregen.running;
container.innerHTML = `
<p class="hint">${escapeHtml(t("tts.hint"))}</p>
<div class="form-grid cols-2">
<label><span>${escapeHtml(t("tts.engine"))}</span>
<select id="ttsEngine">
<option value="browser" ${engine === "browser" ? "selected" : ""}>${escapeHtml(t("tts.engine_browser"))}</option>
<option value="piper" ${engine === "piper" ? "selected" : ""}>${escapeHtml(t("tts.engine_piper"))}</option>
</select>
</label>
<div>
<p><strong>${escapeHtml(status?.available ? t("tts.status_ready") : t("tts.status_missing"))}</strong></p>
<p class="hint">${LANGUAGES.map((language) => `${language === "sv" ? "Svenska" : "English"}: ${hasLanguage(language) ? "✓" : "✗"}`).join(" · ")} · ${escapeHtml(t("tts.cached", { count: status?.cachedLines || 0 }))}</p>
</div>
</div>
<div class="actions">
<button class="btn" type="button" id="ttsInstall" ${busy ? "disabled" : ""}>${escapeHtml(t(status?.available && hasLanguage("sv") && hasLanguage("en") ? "tts.reinstall" : "tts.install"))}</button>
<button class="btn" type="button" id="ttsPregenerate" ${busy || !status?.available ? "disabled" : ""}>${escapeHtml(t("tts.pregenerate"))}</button>
<button class="btn" type="button" id="ttsTest" ${!status?.available ? "disabled" : ""}>${escapeHtml(t("tts.test"))}</button>
</div>
${install.running || install.log?.length ? `<pre class="log-box">${escapeHtml((install.log || []).join("\n"))}${install.error ? `\n${escapeHtml(install.error)}` : ""}</pre>` : ""}
${pregen.total ? `<p class="hint">${escapeHtml(t("tts.pregenerate_progress", { done: pregen.done, total: pregen.total, failed: pregen.failed }))}</p>` : ""}`;
container.querySelector("#ttsEngine").addEventListener("change", (event) => {
state.settings.ttsEngine = event.target.value === "piper" ? "piper" : "browser";
saveState();
});
container.querySelector("#ttsInstall").addEventListener("click", async () => {
await fetch("/api/tts/install", { method: "POST" });
remount();
});
container.querySelector("#ttsPregenerate").addEventListener("click", async () => {
await fetch("/api/tts/pregenerate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: await buildPregenerateItems(state) }) });
remount();
});
container.querySelector("#ttsTest").addEventListener("click", () => {
const language = state.settings.raceAudio?.language === "en" ? "en" : "sv";
speakText(SAMPLES[language], { interrupt: true, language });
});
// Keep polling while a background install/pre-generation is running.
if (busy) setTimeout(() => { if (container.isConnected) remount(); }, 1500);
}