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.
This commit is contained in:
PeymanHonarjoo
2026-10-08 12:52:29 +03:30
parent 447849289e
commit f6ce43453a
15 changed files with 2152 additions and 49 deletions
@@ -2,14 +2,6 @@
display: block;
}
:host-context(.has-messages) {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
.ai-chat-input-wrapper {
width: 100%;
max-width: 800px;
@@ -27,9 +19,7 @@
/* Layers cross-fade */
.composer-layer,
.voice-layer {
transition:
opacity 0.35s ease,
transform 0.35s ease;
transition: opacity 0.35s ease, transform 0.35s ease;
}
.composer-layer {
@@ -57,6 +47,13 @@
transform: translateY(0) scale(1);
pointer-events: auto;
}
:host-context(.has-messages) {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
/* ---------- Chat composer ---------- */
.chat-composer {
@@ -69,30 +66,26 @@
padding: 0.625rem 0.75rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 2rem;
box-shadow:
0 2px 12px rgba(0, 0, 0, 0.05),
0 1px 3px rgba(0, 0, 0, 0.03);
transition:
box-shadow 0.2s ease,
border-color 0.2s ease;
border-radius: 1.5rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
transition: box-shadow 0.2s ease, border-color 0.2s ease;
position: relative;
}
.chat-composer:focus-within {
border-color: var(--color-primary);
box-shadow:
0 4px 20px rgba(59, 130, 246, 0.12),
0 1px 3px rgba(0, 0, 0, 0.03);
box-shadow: 0 4px 20px rgba(59, 130, 246, 0.12), 0 1px 3px rgba(0, 0, 0, 0.03);
}
.composer-textarea-wrapper {
flex: 1;
min-width: 0;
align-self: stretch;
}
.composer-textarea {
width: 100%;
height: 100%;
min-height: 24px;
max-height: 192px;
padding: 0.375rem 0;
@@ -140,10 +133,7 @@
background: transparent;
color: var(--muted);
cursor: pointer;
transition:
background 0.2s ease,
color 0.2s ease,
transform 0.15s ease;
transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease;
flex-shrink: 0;
user-select: none;
}
@@ -208,9 +198,7 @@
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 0.875rem;
box-shadow:
0 8px 30px rgba(0, 0, 0, 0.12),
0 2px 8px rgba(0, 0, 0, 0.06);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
overflow: hidden;
z-index: 50;
animation: menuFadeIn 0.15s ease;
@@ -318,9 +306,7 @@
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 1.5rem;
box-shadow:
0 2px 12px rgba(0, 0, 0, 0.05),
0 1px 3px rgba(0, 0, 0, 0.03);
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
}
.orb-container {
@@ -447,11 +433,7 @@
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition:
background 0.2s ease,
color 0.2s ease,
border-color 0.2s ease,
transform 0.15s ease;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
@@ -571,3 +553,35 @@
min-width: 160px;
}
}
/* ---------- Live voice call (taller view for the running transcript) ---------- */
.ai-chat-input-wrapper.stream-active {
min-height: min(580px, 78vh);
}
.send-btn svg {
animation: sendIconIn 0.18s ease;
}
@keyframes sendIconIn {
from {
opacity: 0;
transform: scale(0.7);
}
to {
opacity: 1;
transform: scale(1);
}
}
@media (prefers-reduced-motion: reduce) {
.send-btn svg {
animation: none !important;
}
}
@media (max-width: 640px) {
.ai-chat-input-wrapper.stream-active {
min-height: min(540px, 80vh);
}
}
@@ -1,13 +1,14 @@
<div
class="ai-chat-input-wrapper"
[class.voice-active]="isVoiceMode()"
[class.voice-active]="anyVoiceActive()"
[class.stream-active]="streamOpen()"
[attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()"
>
<!-- Announces every voice state change to screen readers -->
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<div class="composer-layer" [attr.inert]="isVoiceMode() ? '' : null">
<div class="composer-layer" [attr.inert]="anyVoiceActive() ? '' : null">
<div class="chat-composer" #composer>
<button
#plusBtn
@@ -61,13 +62,26 @@
<button
type="button"
class="composer-btn send-btn"
[disabled]="!message().trim() || disabled()"
(click)="sendMessage()"
aria-label="ارسال پیام"
[class.is-voice-call]="!canSend()"
[disabled]="disabled()"
[attr.aria-label]="actionLabel()"
[attr.title]="actionLabel()"
(click)="onPrimaryAction()"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 19V5M5 12l7-7 7 7" />
</svg>
@if (canSend()) {
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 19V5M5 12l7-7 7 7" />
</svg>
} @else {
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M2 10v3" />
<path d="M6 6v11" />
<path d="M10 3v18" />
<path d="M14 8v7" />
<path d="M18 5v13" />
<path d="M22 10v3" />
</svg>
}
</button>
@if (isAttachmentMenuOpen()) {
@@ -136,9 +150,12 @@
<div
class="voice-layer"
[attr.inert]="isVoiceMode() ? null : ''"
[attr.aria-hidden]="isVoiceMode() ? null : 'true'"
[attr.inert]="anyVoiceActive() ? null : ''"
[attr.aria-hidden]="anyVoiceActive() ? null : 'true'"
>
@if (layerMode() === 'stream') {
<app-voice-stream-panel />
} @else {
<div class="voice-mode" role="region" aria-label="حالت صوتی">
<div class="orb-container" #orbContainer aria-hidden="true">
@if (!orbAvailable()) {
@@ -190,5 +207,6 @@
</button>
</div>
</div>
}
</div>
</div>
@@ -1,3 +1,4 @@
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
ChangeDetectionStrategy,
Component,
@@ -21,6 +22,9 @@ import {
SpeechTranscript,
} from '../../../services/speech-recognition/speech-recognition.service';
import { VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceMessage } from '../../../services/voice-stream/voice-stream.types';
import { VoiceStreamPanelComponent } from '../voice-stream-panel/voice-stream-panel.component';
export type VoiceState =
| 'idle'
@@ -49,6 +53,8 @@ export const DEFAULT_ATTACHMENT_ACTIONS: readonly AttachmentAction[] = [
];
const NOTICE_TIMEOUT_MS = 7000;
/** Keeps the previous voice view mounted while the layer fades out (matches the 0.35 s CSS fade). */
const LAYER_SWAP_MS = 400;
const MIC_ERRORS: Record<string, string> = {
unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمی‌کند (اتصال امن HTTPS لازم است).',
@@ -70,6 +76,7 @@ const SPEECH_ERRORS: Record<SpeechErrorKind, string> = {
@Component({
selector: 'app-ai-chat-input',
standalone: true,
imports: [VoiceStreamPanelComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './ai-chat-input.component.html',
styleUrl: './ai-chat-input.component.css',
@@ -79,6 +86,7 @@ export class AiChatInputComponent implements OnDestroy {
private readonly voiceOrb = inject(VoiceOrbService);
private readonly mic = inject(MicrophoneService);
private readonly speech = inject(SpeechRecognitionService);
private readonly voiceStream = inject(VoiceStreamService);
// ---- API ------------------------------------------------------------------
readonly placeholder = input<string>('پیام خود را بنویسید...');
@@ -91,6 +99,8 @@ export class AiChatInputComponent implements OnDestroy {
readonly messageSent = output<string>();
readonly fileSelected = output<File>();
readonly voiceToggled = output<boolean>();
/** Emitted when a live voice call ends, with the full two-sided transcript. */
readonly voiceSessionEnded = output<VoiceMessage[]>();
// ---- state ----------------------------------------------------------------
readonly message = signal('');
@@ -102,6 +112,14 @@ export class AiChatInputComponent implements OnDestroy {
readonly liveInterim = signal('');
readonly orbAvailable = signal(true);
// Live voice call (voice-to-voice stream)
readonly streamOpen = this.voiceStream.isOpen;
/** Which view the voice layer shows; swapped after the fade so nothing flashes. */
readonly layerMode = signal<'dictation' | 'stream'>('dictation');
readonly canSend = computed(() => !!this.message().trim());
readonly anyVoiceActive = computed(() => this.isVoiceMode() || this.streamOpen());
readonly actionLabel = computed(() => (this.canSend() ? 'ارسال پیام' : 'شروع گفتگوی صوتی'));
readonly voiceSupported = this.mic.isSupported && this.speech.isSupported;
/** The orb view replaces the composer while recording, transcribing and stopping. */
@@ -155,6 +173,7 @@ export class AiChatInputComponent implements OnDestroy {
/** Textarea content when recording started; dictated text is appended to it. */
private baseText = '';
private noticeTimer: ReturnType<typeof setTimeout> | null = null;
private layerTimer: ReturnType<typeof setTimeout> | null = null;
constructor() {
// The outside-click listener only exists while the menu is open.
@@ -169,13 +188,23 @@ export class AiChatInputComponent implements OnDestroy {
document.addEventListener('mousedown', onMouseDown);
onCleanup(() => document.removeEventListener('mousedown', onMouseDown));
});
this.voiceStream.sessionEnded$.pipe(takeUntilDestroyed()).subscribe(({ messages, error }) => {
this.voiceToggled.emit(false);
this.voiceSessionEnded.emit(messages);
if (error) this.showNotice({ kind: 'error', text: error });
this.scheduleLayerReset();
this.focusTextarea();
});
}
ngOnDestroy(): void {
this.voiceSession++;
this.speech.dispose();
this.mic.release();
this.voiceStream.dispose();
this.voiceOrb.dispose();
if (this.layerTimer) clearTimeout(this.layerTimer);
this.clearNoticeTimer();
}
@@ -297,11 +326,61 @@ export class AiChatInputComponent implements OnDestroy {
if (this.isAttachmentMenuOpen()) {
this.closeAttachmentMenu();
this.plusBtnRef()?.nativeElement.focus();
} else if (this.streamOpen()) {
this.voiceStream.end();
} else if (this.isVoiceMode()) {
void this.stopVoice(true);
}
}
// ---- live voice call (voice-to-voice stream) --------------------------------
/** Send arrow when there is text, waveform (start call) when the textarea is empty. */
onPrimaryAction(): void {
if (this.canSend()) {
this.sendMessage();
} else {
void this.startVoiceStream();
}
}
async startVoiceStream(): Promise<void> {
if (this.disabled() || this.streamOpen()) return;
const dictating = this.voiceState() !== 'idle' && this.voiceState() !== 'error';
if (dictating) return;
this.dismissNotice();
this.closeAttachmentMenu();
this.cancelLayerReset();
this.layerMode.set('stream');
this.voiceToggled.emit(true);
const result = await this.voiceStream.start();
if (!result.ok) {
// The call never connected, so no sessionEnded event is emitted for it.
this.voiceToggled.emit(false);
this.scheduleLayerReset();
if (result.reason !== 'cancelled') {
this.showNotice({ kind: 'error', text: result.message });
}
}
}
private scheduleLayerReset(): void {
this.cancelLayerReset();
this.layerTimer = setTimeout(() => {
this.layerTimer = null;
if (!this.streamOpen()) this.layerMode.set('dictation');
}, LAYER_SWAP_MS);
}
private cancelLayerReset(): void {
if (this.layerTimer) {
clearTimeout(this.layerTimer);
this.layerTimer = null;
}
}
// ---- voice: start ---------------------------------------------------------
async toggleVoiceMode(): Promise<void> {
@@ -322,8 +401,10 @@ export class AiChatInputComponent implements OnDestroy {
}
private async startVoice(): Promise<void> {
if (this.disabled()) return;
if (this.disabled() || this.streamOpen()) return;
this.cancelLayerReset();
this.layerMode.set('dictation');
this.dismissNotice();
this.closeAttachmentMenu();
@@ -0,0 +1,374 @@
:host {
display: block;
height: 100%;
}
.stream-panel {
direction: rtl;
box-sizing: border-box;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 1rem 1.25rem 1.25rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 1.5rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
}
/* ---------- Orb ---------- */
.orb-container {
width: 170px;
height: 170px;
max-width: 100%;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.orb-container canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
.orb-fallback {
width: 70%;
height: 70%;
border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f);
box-shadow: 0 0 40px rgba(59, 130, 246, 0.35);
animation: fallbackPulse 2.4s ease-in-out infinite;
}
@keyframes fallbackPulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.06);
}
}
/* ---------- Status ---------- */
.stream-status {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.status-text {
margin: 0;
font-size: 0.9375rem;
color: var(--text-secondary);
text-align: center;
}
.status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--muted);
flex-shrink: 0;
transition: background 0.3s ease;
}
.stream-status[data-state='LISTENING'] .status-dot {
background: #22c55e;
animation: dotPulse 1.6s ease-in-out infinite;
}
.stream-status[data-state='PROCESSING'] .status-dot {
background: #818cf8;
animation: dotPulse 0.9s ease-in-out infinite;
}
.stream-status[data-state='SPEAKING'] .status-dot {
background: #a78bfa;
animation: dotPulse 0.7s ease-in-out infinite;
}
.stream-status[data-state='INTERRUPTED'] .status-dot {
background: #f59e0b;
}
@keyframes dotPulse {
0%,
100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.55;
transform: scale(1.3);
}
}
/* ---------- Transcript ---------- */
.stream-transcript {
flex: 1;
min-height: 0;
width: 100%;
max-width: 640px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.25rem 0.25rem;
scroll-behavior: smooth;
}
.stream-transcript::-webkit-scrollbar {
width: 4px;
}
.stream-transcript::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
/* RTL: user bubbles sit on the right (start), assistant bubbles on the left (end). */
.bubble-row {
display: flex;
justify-content: flex-end;
}
.bubble-row.is-user {
justify-content: flex-start;
}
.bubble {
max-width: 85%;
padding: 0.5rem 0.875rem;
border-radius: 1.125rem;
background: var(--sidebar-hover);
color: var(--text-primary);
font-size: 0.9375rem;
line-height: 1.7;
text-align: right;
white-space: pre-wrap;
overflow-wrap: anywhere;
border-end-end-radius: 0.375rem;
transition: opacity 0.2s ease;
}
.bubble.is-user {
background: var(--color-primary);
color: #ffffff;
border-end-end-radius: 1.125rem;
border-end-start-radius: 0.375rem;
}
.bubble.is-partial {
opacity: 0.7;
}
.bubble.is-interrupted .bubble-text {
opacity: 0.8;
}
.bubble-tag {
margin-inline-start: 0.375rem;
font-size: 0.75rem;
opacity: 0.7;
}
/* ---------- Sources (retrieved documents) ---------- */
.source-list {
list-style: none;
margin: 0.375rem 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.source-chip {
display: flex;
align-items: baseline;
gap: 0.375rem;
padding: 0.25rem 0.5rem;
border: 1px solid var(--surface-border);
border-radius: 0.625rem;
background: var(--surface-bg);
color: var(--text-secondary);
font-size: 0.75rem;
line-height: 1.5;
}
.source-chip.is-unavailable {
opacity: 0.55;
text-decoration: line-through;
}
.source-ref {
flex-shrink: 0;
padding: 0 0.375rem;
border-radius: 9999px;
background: var(--color-primary);
color: #ffffff;
font-size: 0.6875rem;
font-weight: 600;
}
/* ---------- Retryable server error ---------- */
.stream-error {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
max-width: 640px;
box-sizing: border-box;
padding: 0.5rem 0.75rem;
border: 1px solid rgba(239, 68, 68, 0.45);
border-radius: 0.875rem;
color: #dc2626;
font-size: 0.8125rem;
line-height: 1.6;
flex-shrink: 0;
}
.stream-error span {
flex: 1;
min-width: 0;
}
.stream-error-close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: none;
border-radius: 50%;
background: transparent;
color: inherit;
cursor: pointer;
flex-shrink: 0;
}
.stream-error-close:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
/* ---------- Actions ---------- */
.stream-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
flex-wrap: wrap;
flex-shrink: 0;
}
.stream-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border: 1px solid var(--surface-border);
border-radius: 9999px;
background: var(--surface-bg);
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
.stream-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.03);
}
.stream-btn:active:not(:disabled) {
transform: scale(0.97);
}
.stream-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.stream-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.stream-btn.is-active {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.5);
color: #dc2626;
}
.stream-btn.is-end {
background: #ef4444;
border-color: #ef4444;
color: #ffffff;
}
.stream-btn.is-end:hover:not(:disabled) {
background: #dc2626;
border-color: #dc2626;
color: #ffffff;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (prefers-reduced-motion: reduce) {
.status-dot,
.orb-fallback,
.stream-btn,
.bubble,
.stream-transcript {
animation: none !important;
transition: none !important;
scroll-behavior: auto !important;
}
}
@media (max-width: 640px) {
.stream-panel {
gap: 0.5rem;
padding: 0.75rem 0.75rem 1rem;
}
.orb-container {
width: 130px;
height: 130px;
}
.bubble {
max-width: 92%;
font-size: 0.875rem;
}
.stream-btn {
padding: 0.5rem 1rem;
}
}
@@ -0,0 +1,102 @@
<div class="stream-panel" role="region" aria-label="گفتگوی صوتی" [attr.data-state]="state()">
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<div class="orb-container" #orbContainer aria-hidden="true">
@if (!orbAvailable()) {
<div class="orb-fallback"></div>
}
</div>
<div class="stream-status" [attr.data-state]="state()">
<span class="status-dot" aria-hidden="true"></span>
<p class="status-text">{{ statusText() }}</p>
</div>
@if (streamError(); as errorText) {
<div class="stream-error" role="alert">
<span>{{ errorText }}</span>
<button type="button" class="stream-error-close" aria-label="بستن پیام" (click)="dismissError()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
<div class="stream-transcript" #scroller role="log" aria-label="متن گفتگو" aria-live="polite" aria-relevant="additions">
@for (message of messages(); track message.role + message.id) {
<div class="bubble-row" [class.is-user]="message.role === 'user'">
<div
class="bubble"
[class.is-user]="message.role === 'user'"
[class.is-partial]="!message.final"
[class.is-interrupted]="message.interrupted"
dir="rtl"
>
@if (message.text) {
<span class="bubble-text">{{ message.text }}</span>
}
@if (message.interrupted) {
<span class="bubble-tag">(قطع شد)</span>
}
@if (message.sources?.length) {
<ul class="source-list" aria-label="منابع پاسخ">
@for (source of message.sources ?? []; track source.source_ref + source.chunk_id) {
<li
class="source-chip"
[class.is-unavailable]="source.available === false"
[attr.title]="source.excerpt ?? null"
>
<span class="source-ref">{{ source.source_ref }}</span>
<span class="source-label">{{ sourceLabel(source) }}</span>
</li>
}
</ul>
}
</div>
</div>
} @empty {
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
}
</div>
<div class="stream-actions">
<button
type="button"
class="stream-btn"
[class.is-active]="muted()"
[attr.aria-pressed]="muted()"
[attr.aria-label]="muteLabel()"
[attr.title]="muteLabel()"
[disabled]="connection() !== 'connected'"
(click)="toggleMute()"
>
@if (muted()) {
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="2" x2="22" y1="2" y2="22" />
<path d="M18.89 13.23A7.12 7.12 0 0 0 19 12v-2" />
<path d="M5 10v2a7 7 0 0 0 12 5" />
<path d="M15 9.34V5a3 3 0 0 0-5.68-1.33" />
<path d="M9 9v3a3 3 0 0 0 5.12 2.12" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
} @else {
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
}
<span>{{ muted() ? 'فعال‌سازی' : 'بی‌صدا' }}</span>
</button>
<button type="button" class="stream-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
<span>پایان گفتگو</span>
</button>
</div>
</div>
@@ -0,0 +1,116 @@
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
OnDestroy,
computed,
effect,
inject,
signal,
viewChild,
} from '@angular/core';
import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceSource, VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
IDLE: 'listening',
LISTENING: 'listening',
INTERRUPTED: 'listening',
PROCESSING: 'processing',
SPEAKING: 'speaking',
};
/** Live call view: orb, status, running two-sided transcript, mute / end controls. */
@Component({
selector: 'app-voice-stream-panel',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './voice-stream-panel.component.html',
styleUrl: './voice-stream-panel.component.css',
})
export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
private readonly voice = inject(VoiceStreamService);
private readonly orb = inject(VoiceOrbService);
readonly state = this.voice.state;
readonly connection = this.voice.connection;
readonly messages = this.voice.messages;
readonly muted = this.voice.muted;
readonly streamError = this.voice.streamError;
readonly orbAvailable = signal(true);
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
readonly statusText = computed(() => {
if (this.connection() === 'connecting') return 'در حال اتصال...';
if (this.connection() === 'disconnected') return 'گفتگو پایان یافت';
switch (this.state()) {
case 'LISTENING':
return this.muted() ? 'میکروفون بی‌صدا است' : 'در حال گوش دادن...';
case 'PROCESSING':
return 'در حال پردازش...';
case 'SPEAKING':
return 'در حال پاسخ دادن... (برای قطع کردن صحبت کنید)';
case 'INTERRUPTED':
return 'پاسخ قطع شد';
default:
return '';
}
});
readonly muteLabel = computed(() =>
this.muted() ? 'فعال‌سازی میکروفون' : 'بی‌صدا کردن میکروفون',
);
constructor() {
effect(() => this.orb.setMode(ORB_MODE[this.state()]));
// Keep the newest message in view as text streams in.
effect(() => {
this.messages();
requestAnimationFrame(() => {
const el = this.scroller()?.nativeElement;
if (el) el.scrollTop = el.scrollHeight;
});
});
}
ngAfterViewInit(): void {
const ready = this.orb.init(this.orbContainer().nativeElement);
this.orbAvailable.set(ready);
if (!ready) return;
this.orb.resetOrbGeometry();
this.orb.setLevelProvider(() => this.voice.orbLevel());
this.orb.startAnimation();
}
ngOnDestroy(): void {
this.orb.stopAnimation();
this.orb.setLevelProvider(null);
this.orb.setMode('listening');
}
/** "عنوان — صفحه ۱، بند ۲" */
sourceLabel(source: VoiceSource): string {
const parts: string[] = [];
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
if (source.location?.section) parts.push(source.location.section);
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title;
}
dismissError(): void {
this.voice.dismissError();
}
toggleMute(): void {
this.voice.toggleMute();
}
endCall(): void {
this.voice.end();
}
}