/** Browser microphone helpers: lossless WAV recording and low-latency streaming. */ export function microphoneSupportMessage() { if (!window.isSecureContext) { return "Der Browser erlaubt Mikrofonzugriff nur über HTTPS oder localhost. Öffne die Oberfläche über eine sichere Adresse."; } if (!navigator.mediaDevices?.getUserMedia) { return "Dieser Browser stellt keinen Mikrofonzugriff zur Verfügung."; } return null; } export function formatDbFS(level) { return Number.isFinite(level) && level > 0 ? (20 * Math.log10(level)).toFixed(1) : "−∞"; } export async function playOutputTest(context = null) { const owned = !context; context ||= new AudioContext(); try { await context.resume(); const oscillator = context.createOscillator(); const gain = context.createGain(); oscillator.frequency.value = 440; gain.gain.setValueAtTime(0, context.currentTime); gain.gain.linearRampToValueAtTime(0.05, context.currentTime + 0.02); gain.gain.setValueAtTime(0.05, context.currentTime + 0.35); gain.gain.linearRampToValueAtTime(0, context.currentTime + 0.4); oscillator.connect(gain).connect(context.destination); const ended = new Promise(resolve => { oscillator.onended = resolve; }); oscillator.start(); oscillator.stop(context.currentTime + 0.42); await ended; oscillator.disconnect(); gain.disconnect(); } finally { if (owned) await context.close(); } } function encodeWav(chunks, sampleRate) { const length = chunks.reduce((sum, chunk) => sum + chunk.length, 0); const buffer = new ArrayBuffer(44 + length * 2); const view = new DataView(buffer); const write = (offset, value) => { for (let i = 0; i < value.length; i++) view.setUint8(offset + i, value.charCodeAt(i)); }; write(0, "RIFF"); view.setUint32(4, 36 + length * 2, true); write(8, "WAVE"); write(12, "fmt "); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true); write(36, "data"); view.setUint32(40, length * 2, true); let offset = 44; for (const chunk of chunks) { for (let i = 0; i < chunk.length; i++) { const sample = Math.max(-1, Math.min(1, chunk[i])); view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true); offset += 2; } } return new Blob([buffer], { type: "audio/wav" }); } export class WavRecorder { constructor() { this.stream = null; this.context = null; this.source = null; this.processor = null; this.sink = null; this.chunks = []; this.startedAt = 0; } async start() { const unsupported = microphoneSupportMessage(); if (unsupported) throw new Error(unsupported); this.stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false, }, }); this.context = new AudioContext({ latencyHint: "interactive" }); this.source = this.context.createMediaStreamSource(this.stream); this.processor = this.context.createScriptProcessor(4096, 1, 1); this.sink = this.context.createGain(); this.sink.gain.value = 0; this.chunks = []; this.processor.onaudioprocess = (event) => { this.chunks.push(new Float32Array(event.inputBuffer.getChannelData(0))); }; this.source.connect(this.processor); this.processor.connect(this.sink); this.sink.connect(this.context.destination); this.startedAt = performance.now(); } async stop() { if (!this.context) throw new Error("Es läuft keine Aufnahme"); const sampleRate = this.context.sampleRate; const duration = (performance.now() - this.startedAt) / 1000; this.processor.disconnect(); this.source.disconnect(); this.sink.disconnect(); this.stream.getTracks().forEach((track) => track.stop()); await this.context.close(); const blob = encodeWav(this.chunks, sampleRate); this.stream = this.context = this.source = this.processor = this.sink = null; this.chunks = []; return { blob, sampleRate, duration }; } async cancel() { if (this.stream) this.stream.getTracks().forEach((track) => track.stop()); if (this.context && this.context.state !== "closed") await this.context.close(); this.stream = this.context = this.source = this.processor = this.sink = null; this.chunks = []; } } const INPUT_WORKLET = ` class MicInputProcessor extends AudioWorkletProcessor { constructor(options) { super(); this.size = options.processorOptions.blockFrame; this.buffer = new Float32Array(this.size); this.offset = 0; } process(inputs) { const input = inputs[0] && inputs[0][0]; if (!input) return true; let cursor = 0; while (cursor < input.length) { const count = Math.min(input.length - cursor, this.size - this.offset); this.buffer.set(input.subarray(cursor, cursor + count), this.offset); cursor += count; this.offset += count; if (this.offset === this.size) { const ready = this.buffer; this.port.postMessage(ready.buffer, [ready.buffer]); this.buffer = new Float32Array(this.size); this.offset = 0; } } return true; } } registerProcessor("mic-input", MicInputProcessor);`; const PLAYBACK_WORKLET = ` class VoicePlaybackProcessor extends AudioWorkletProcessor { constructor() { super(); this.queue = []; this.current = null; this.offset = 0; this.port.onmessage = event => this.queue.push(new Float32Array(event.data)); } process(_inputs, outputs) { const output = outputs[0][0]; output.fill(0); let written = 0; while (written < output.length) { if (!this.current || this.offset >= this.current.length) { this.current = this.queue.shift() || null; this.offset = 0; if (!this.current) break; } const count = Math.min(output.length - written, this.current.length - this.offset); output.set(this.current.subarray(this.offset, this.offset + count), written); this.offset += count; written += count; } return true; } } registerProcessor("voice-playback", VoicePlaybackProcessor);`; async function addWorklet(context, source) { const url = URL.createObjectURL(new Blob([source], { type: "text/javascript" })); try { await context.audioWorklet.addModule(url); } finally { URL.revokeObjectURL(url); } } export class RealtimeVoiceClient { constructor({ onStatus, onLatency, onError, onOutput = () => {} }) { this.onStatus = onStatus; this.onLatency = onLatency; this.onError = onError; this.onOutput = onOutput; this.outputLevel = 1; this.stream = this.context = this.socket = null; } async start(parameters) { const unsupported = microphoneSupportMessage(); if (unsupported) throw new Error(unsupported); this.onStatus("Mikrofon wird geöffnet …"); this.stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: { ideal: 1 }, sampleRate: { ideal: 48000 }, echoCancellation: true, noiseSuppression: true, autoGainControl: false, }, }); this.context = new AudioContext({ sampleRate: 48000, latencyHint: "interactive" }); if (this.context.sampleRate !== 48000) { throw new Error(`Das Audiogerät läuft mit ${this.context.sampleRate} Hz statt benötigten 48000 Hz`); } await Promise.all([ addWorklet(this.context, INPUT_WORKLET), addWorklet(this.context, PLAYBACK_WORKLET), ]); const protocol = location.protocol === "https:" ? "wss:" : "ws:"; this.socket = new WebSocket(`${protocol}//${location.host}/api/realtime/audio`); this.socket.binaryType = "arraybuffer"; const configuration = await new Promise((resolve, reject) => { let configured = false; let failed = false; const fail = (message) => { if (failed) return; failed = true; clearTimeout(timer); if (!configured) reject(new Error(message)); else { void this.stop(); this.onError(message); } }; const timer = setTimeout(() => fail("Echtzeitdienst antwortet nicht"), 60000); this.socket.onopen = () => { this.socket.send(JSON.stringify(parameters)); }; this.socket.onerror = () => { fail("WebSocket-Verbindung zum Echtzeitdienst fehlgeschlagen"); }; this.socket.onmessage = (event) => { if (typeof event.data === "string") { let message; try { message = JSON.parse(event.data); } catch { fail("Ungültige Antwort des Echtzeitdiensts"); return; } if (message.type === "configured" && !configured) { if (message.sample_rate !== 48000 || !Number.isInteger(message.block_frame) || message.block_frame < 128 || message.block_frame > 24064 || message.block_frame % 128 !== 0) { fail("Ungültige Audiokonfiguration des Echtzeitdiensts"); return; } configured = true; clearTimeout(timer); this.onStatus("Echtzeitmodell wird vorbereitet …"); resolve(message); } if (message.type === "ready") this.onStatus("Live – sprich jetzt ins Mikrofon"); if (message.type === "latency") this.onLatency(message.value, message.volume); if (message.type === "error") fail(message.value); return; } const samples = new Float32Array(event.data); let energy = 0; for (const value of samples) energy += value * value; this.onOutput(samples.length ? Math.sqrt(energy / samples.length) * this.outputLevel : 0); this.playback?.port.postMessage(event.data, [event.data]); }; this.socket.onclose = (event) => { fail(event.reason || "Die Verbindung zum Echtzeitdienst wurde beendet. Bitte erneut starten."); }; }); const source = this.context.createMediaStreamSource(this.stream); const input = new AudioWorkletNode(this.context, "mic-input", { processorOptions: { blockFrame: configuration.block_frame }, }); const silentSink = this.context.createGain(); silentSink.gain.value = 0; const playback = new AudioWorkletNode(this.context, "voice-playback", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [1], }); const outputGain = this.context.createGain(); outputGain.gain.value = this.outputLevel; source.connect(input); input.connect(silentSink).connect(this.context.destination); playback.connect(outputGain).connect(this.context.destination); input.port.onmessage = (event) => { if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(event.data); }; this.source = source; this.input = input; this.silentSink = silentSink; this.playback = playback; this.outputGain = outputGain; if (this.context.state === "suspended") await this.context.resume(); } setOutputLevel(level) { this.outputLevel = Math.max(0, Math.min(3, Number(level) || 0)); if (this.outputGain) this.outputGain.gain.value = this.outputLevel; } async stop() { if (this.socket) { this.socket.onclose = this.socket.onerror = this.socket.onmessage = null; if (this.socket.readyState < WebSocket.CLOSING) this.socket.close(1000, "Beendet"); } [this.source, this.input, this.silentSink, this.playback, this.outputGain].forEach((node) => { try { node?.disconnect(); } catch { /* already disconnected */ } }); this.stream?.getTracks().forEach((track) => track.stop()); const context = this.context; this.stream = this.context = this.socket = null; this.source = this.input = this.silentSink = this.playback = null; this.outputGain = null; if (context && context.state !== "closed") await context.close(); } }