feat(voice): add audio cues for session lifecycle

Introduce VoiceCueService to play 'ready' and 'end' audio cues during
voice stream sessions. This provides auditory feedback when a session
starts and concludes.
This commit is contained in:
PeymanHonarjoo
2026-10-11 17:25:44 +03:30
parent a6c466e1ba
commit e268631386
4 changed files with 163 additions and 0 deletions
@@ -0,0 +1,152 @@
import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core';
export type VoiceCueKind = 'ready' | 'end';
const CUE_ASSETS: Record<VoiceCueKind, string> = {
ready: 'assets/audio/voice-ready.wav',
end: 'assets/audio/voice-end.wav',
};
/**
* Plays the short reference cues extracted from the supplied recording.
*
* Unlike the previous synthesized version, this service plays the original
* recorded waveform. Do not add a convolver/reverb to it: the reference cue
* already contains its original tone and tail.
*/
@Injectable({ providedIn: 'root' })
export class VoiceCueService {
private readonly document = inject(DOCUMENT);
private ctx: AudioContext | null = null;
private readonly buffers = new Map<VoiceCueKind, AudioBuffer>();
private readonly pending = new Map<VoiceCueKind, Promise<AudioBuffer | null>>();
private enabled = true;
/** Disable or enable subsequent cues. */
setEnabled(on: boolean): void {
this.enabled = on;
}
/**
* Optional warm-up. Call once when the voice UI/component initializes,
* so fetching and decoding do not delay the first cue.
*/
async preload(): Promise<void> {
if (typeof AudioContext === 'undefined' || typeof fetch === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
await Promise.all([this.loadBuffer('ready', ctx), this.loadBuffer('end', ctx)]);
} catch {
// Preloading is best-effort; audio must never block the voice UI.
}
}
/** Play the recorded cue when the voice session is ready. */
playReady(): void {
void this.play('ready');
}
/** Play the recorded cue when the voice session ends. */
playEnd(): void {
void this.play('end');
}
private async play(kind: VoiceCueKind): Promise<void> {
if (!this.enabled || typeof AudioContext === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
// Request resume immediately, before awaiting fetch/decode, to preserve
// browser user activation when the call originates from a user gesture.
const resumePromise =
ctx.state === 'suspended' ? ctx.resume().catch(() => undefined) : Promise.resolve();
const bufferPromise = this.loadBuffer(kind, ctx);
const [buffer] = await Promise.all([bufferPromise, resumePromise]);
if (!buffer || ctx.state !== 'running') {
return;
}
const source = ctx.createBufferSource();
const output = ctx.createGain();
source.buffer = buffer;
output.gain.setValueAtTime(1, ctx.currentTime);
source.connect(output);
output.connect(ctx.destination);
source.onended = () => {
source.disconnect();
output.disconnect();
};
// A tiny scheduling lead avoids starting mid-render quantum.
source.start(ctx.currentTime + 0.01);
} catch {
// A cue is optional; never let audio playback break session handling.
}
}
private ensureContext(): AudioContext {
if (!this.ctx || this.ctx.state === 'closed') {
this.ctx = new AudioContext({ latencyHint: 'interactive' });
// AudioBuffers are decoded against a particular context. Rebuild them
// when that context is recreated.
this.buffers.clear();
this.pending.clear();
}
return this.ctx;
}
private loadBuffer(kind: VoiceCueKind, ctx: AudioContext): Promise<AudioBuffer | null> {
const cached = this.buffers.get(kind);
if (cached) {
return Promise.resolve(cached);
}
const inFlight = this.pending.get(kind);
if (inFlight) {
return inFlight;
}
const assetUrl = new URL(CUE_ASSETS[kind], this.document.baseURI).href;
const promise = fetch(assetUrl, { cache: 'force-cache' })
.then((response) => {
if (!response.ok) {
throw new Error(`Unable to load voice cue: ${response.status}`);
}
return response.arrayBuffer();
})
.then((bytes) => ctx.decodeAudioData(bytes))
.then((buffer) => {
if (this.ctx === ctx) {
this.buffers.set(kind, buffer);
}
return buffer;
})
.catch(() => {
// Let a later call retry if the asset was temporarily unavailable.
if (this.ctx === ctx) {
this.pending.delete(kind);
}
return null;
});
this.pending.set(kind, promise);
return promise;
}
}
@@ -12,6 +12,7 @@ import {
VoiceSessionEnd,
VoiceStreamState,
} from './voice-stream.types';
import { VoiceCueService } from './voice-cue.service';
export type VoiceStartFailure =
| 'cancelled'
@@ -115,6 +116,7 @@ export class VoiceStreamService {
private readonly api = inject(VoiceApiService);
private readonly config = inject(VOICE_STREAM_CONFIG);
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
private readonly cues = inject(VoiceCueService);
readonly state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected');
@@ -289,6 +291,8 @@ export class VoiceStreamService {
this.connection.set('connected');
this.state.set('LISTENING');
this.streaming = true;
// "You can speak now" — once per session, not per turn (a turn cue would be noise).
this.cues.playReady();
return { ok: true };
}
@@ -805,6 +809,13 @@ export class VoiceStreamService {
// Stop admitting new media BEFORE any await.
this.streaming = false;
// "Call finished" — once per connected session, before local resources (including the
// engine AudioContext) are released; every end path funnels through this single-flight
// cleanup, so ordered and unordered teardown both trigger it exactly once.
if (wasConnected) {
this.cues.playEnd();
}
const release = (): void => {
// A newer session may have taken over during an await: never touch its resources.
if (superseded()) return;