diff --git a/public/assets/audio/voice-end.wav b/public/assets/audio/voice-end.wav new file mode 100644 index 0000000..d3b2020 Binary files /dev/null and b/public/assets/audio/voice-end.wav differ diff --git a/public/assets/audio/voice-ready.wav b/public/assets/audio/voice-ready.wav new file mode 100644 index 0000000..775692e Binary files /dev/null and b/public/assets/audio/voice-ready.wav differ diff --git a/src/app/services/voice-stream/voice-cue.service.ts b/src/app/services/voice-stream/voice-cue.service.ts new file mode 100644 index 0000000..d7ab34c --- /dev/null +++ b/src/app/services/voice-stream/voice-cue.service.ts @@ -0,0 +1,152 @@ +import { DOCUMENT } from '@angular/common'; +import { Injectable, inject } from '@angular/core'; + +export type VoiceCueKind = 'ready' | 'end'; + +const CUE_ASSETS: Record = { + 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(); + private readonly pending = new Map>(); + + 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 { + 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 { + 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 { + 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; + } +} diff --git a/src/app/services/voice-stream/voice-stream.service.ts b/src/app/services/voice-stream/voice-stream.service.ts index 649a3b6..a53e73e 100644 --- a/src/app/services/voice-stream/voice-stream.service.ts +++ b/src/app/services/voice-stream/voice-stream.service.ts @@ -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('IDLE'); readonly connection = signal('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;