Files
nexus/crates/nexus-api/assets/stimmen.js

39 lines
2.3 KiB
JavaScript

// Der Testsatz kommt ausschließlich vom Server; hier wird nur die Stimme gewählt.
(() => {
const status = document.getElementById('probe-status');
const csrf = document.querySelector('input[name=csrf]')?.value;
// Ein einziger Ton-Ausgang für alle Proben, gleich beim ersten Klick geweckt (sonst geht der Anfang verloren
// oder die zweite Probe bleibt stumm). Vor dem Ton liegt eine kurze Stille.
let ctx = null;
const ausgang = () => {
if (!ctx || ctx.state === 'closed') ctx = new AudioContext({sampleRate: 24000});
if (ctx.state !== 'running') ctx.resume();
return ctx;
};
document.querySelectorAll('button.probe').forEach(button => button.addEventListener('click', async () => {
const select = button.closest('tr')?.querySelector('.stimmen-modell');
const modell = select ? select.value : button.dataset.modell;
if (!modell) { status.textContent = 'Kein passendes installiertes Sprachmodell verfügbar.'; return; }
const ton = ausgang();
button.disabled = true;
status.textContent = 'Probehören wird geladen (beim ersten Mal kann das einige Sekunden dauern) …';
try {
const response = await fetch('/ui/modelle/probe', {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': csrf}, credentials: 'same-origin', body: JSON.stringify({model: modell, voice: button.dataset.stimme})});
if (!response.ok) throw new Error('Die Stimme konnte nicht probegehört werden.');
// PCM 24 kHz / 16 Bit / Mono, wie bei der bestehenden Vorlese-Route.
const pcm = await response.arrayBuffer();
const samples = new Int16Array(pcm, 0, Math.floor(pcm.byteLength / 2));
const vorlauf = Math.round(0.3 * 24000);
const buffer = ton.createBuffer(1, vorlauf + samples.length, 24000);
const channel = buffer.getChannelData(0);
for (let i = 0; i < samples.length; i++) channel[vorlauf + i] = samples[i] / 32768;
await ton.resume();
const source = ton.createBufferSource(); source.buffer = buffer; source.connect(ton.destination);
source.onended = () => { status.textContent = ''; };
source.start(ton.currentTime + 0.05);
status.textContent = 'Probehören läuft.';
} catch (_) { status.textContent = 'Die Stimme konnte nicht probegehört werden.'; }
finally { button.disabled = false; }
}));
})();