Files
faq_chatbot_frontend/src/app/services/voice-stream/voice-transport.ts
T
PeymanHonarjoo f6ce43453a feat(voice): implement real-time voice-to-voice streaming engine
Introduce a complete low-level audio processing and streaming pipeline
for live voice conversations.

- Implement `VoiceAudioEngine` using `AudioWorklet` for low-latency
  PCM16 capture and playback.
- Add `pcm-capture` and `pcm-playback` worklets for high-performance
  audio processing outside the main thread.
- Implement `VoiceStreamService` to manage the voice-to-voice state
  machine (LISTENING, PROCESSING, SPEAKING, INTERRUPTED).
- Add `VoiceApiService` for managing conversation and session lifecycle
  via REST and WebSocket.
- Create `VoiceStreamPanelComponent` to display real-time transcripts,
  status indicators, and the animated voice orb.
- Integrate voice streaming into the `AiChatInputComponent` with
  support for seamless UI transitions between text and voice modes.
2026-10-08 12:52:29 +03:30

117 lines
3.3 KiB
TypeScript

import { InjectionToken, inject } from '@angular/core';
import { VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
export interface VoiceTransportHandlers {
onEvent(event: VoiceServerEvent): void;
onAudio(chunk: ArrayBuffer): void;
/** Only called for closes the client did not ask for. */
onClose(info: { clean: boolean; code: number; reason: string }): void;
}
export interface VoiceTransport {
connect(handlers: VoiceTransportHandlers): Promise<void>;
/** PCM16 mono 16 kHz frame. */
sendAudio(frame: ArrayBuffer): void;
close(): void;
}
/** Drop mic frames instead of queueing when the socket is this far behind (~0.5 MB ≈ 16 s of audio). */
const MAX_BUFFERED_BYTES = 512 * 1024;
/**
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the handshake,
* so the page must be served from the same site as the API. The contract has no client→server
* JSON messages: the client only sends binary audio frames.
*/
export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null;
private closedByClient = false;
constructor(
private readonly url: string,
private readonly connectTimeoutMs: number,
) {}
connect(handlers: VoiceTransportHandlers): Promise<void> {
return new Promise<void>((resolve, reject) => {
const ws = new WebSocket(this.url);
ws.binaryType = 'arraybuffer';
this.ws = ws;
let opened = false;
const timer = setTimeout(() => {
reject(new Error('connect-timeout'));
this.close();
}, this.connectTimeoutMs);
ws.onopen = () => {
opened = true;
clearTimeout(timer);
resolve();
};
ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') {
try {
handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent);
} catch {
/* ignore malformed control frames */
}
} else if (event.data instanceof ArrayBuffer) {
handlers.onAudio(event.data);
}
};
ws.onerror = () => {
if (!opened) {
clearTimeout(timer);
reject(new Error('connect-failed'));
}
};
ws.onclose = (event: CloseEvent) => {
clearTimeout(timer);
if (!opened) {
reject(new Error('connect-failed'));
return;
}
if (!this.closedByClient) {
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
}
};
});
}
sendAudio(frame: ArrayBuffer): void {
const ws = this.ws;
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount < MAX_BUFFERED_BYTES) {
ws.send(frame);
}
}
close(): void {
this.closedByClient = true;
const ws = this.ws;
this.ws = null;
if (!ws) return;
ws.onmessage = null;
ws.onerror = null;
try {
ws.close(1000);
} catch {
/* already closed */
}
}
}
/** Replace in tests, or to plug a different transport. */
export const VOICE_TRANSPORT_FACTORY = new InjectionToken<(url: string) => VoiceTransport>(
'VOICE_TRANSPORT_FACTORY',
{
providedIn: 'root',
factory: () => {
const config = inject(VOICE_STREAM_CONFIG);
return (url: string) => new WebSocketVoiceTransport(url, config.connectTimeoutMs);
},
},
);