import { Injectable, NgZone, inject } from '@angular/core'; /* Minimal typings: SpeechRecognition is not part of TypeScript's lib.dom. */ interface SpeechRecognitionAlternativeLike { transcript: string; } interface SpeechRecognitionResultLike { readonly isFinal: boolean; readonly length: number; [index: number]: SpeechRecognitionAlternativeLike; } interface SpeechRecognitionEventLike { readonly resultIndex: number; readonly results: { readonly length: number; [index: number]: SpeechRecognitionResultLike }; } interface SpeechRecognitionErrorEventLike { readonly error: string; } interface SpeechRecognitionLike { lang: string; continuous: boolean; interimResults: boolean; maxAlternatives: number; onresult: ((event: SpeechRecognitionEventLike) => void) | null; onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null; onend: (() => void) | null; onspeechend: (() => void) | null; start(): void; stop(): void; abort(): void; } type SpeechRecognitionCtor = new () => SpeechRecognitionLike; export const DEFAULT_SPEECH_LANGUAGE = 'fa-IR'; export type SpeechErrorKind = | 'permission-denied' | 'audio-capture' | 'network' | 'no-speech' | 'language-not-supported' | 'unsupported' | 'unknown'; export interface SpeechTranscript { /** Confirmed text for the whole session (never contains duplicates). */ final: string; /** Text still being recognized; may change or disappear on the next event. */ interim: string; } export interface SpeechSessionHandlers { onTranscript(transcript: SpeechTranscript): void; onSpeechEnd?(): void; /** Fatal errors only. The session is already over when this is called. */ onError(kind: SpeechErrorKind): void; } /** Silent restarts allowed (Chrome ends sessions after pauses) before reporting "no speech". */ const MAX_SILENT_RESTARTS = 4; const RESTART_DELAY_MS = 250; const STOP_TIMEOUT_MS = 1500; @Injectable({ providedIn: 'root' }) export class SpeechRecognitionService { private readonly ngZone = inject(NgZone); private readonly ctor: SpeechRecognitionCtor | null = this.resolveCtor(); private recognition: SpeechRecognitionLike | null = null; private handlers: SpeechSessionHandlers | null = null; private lang = DEFAULT_SPEECH_LANGUAGE; private running = false; private finalText = ''; private interimText = ''; private silentRestarts = 0; private restartTimer: ReturnType | null = null; private stopTimer: ReturnType | null = null; private stopResolver: ((text: string) => void) | null = null; get isSupported(): boolean { return this.ctor !== null; } /** Final + interim text right now. */ currentText(): string { return this.join(this.finalText, this.interimText); } /** Starts a continuous session. Returns false if it could not be started. */ start(lang: string, handlers: SpeechSessionHandlers): boolean { if (!this.ctor) return false; this.abort(); this.lang = lang || DEFAULT_SPEECH_LANGUAGE; this.handlers = handlers; this.finalText = ''; this.interimText = ''; this.silentRestarts = 0; this.running = true; if (!this.startRecognition()) { this.abort(); return false; } return true; } /** * Stops listening and resolves with the confirmed text, including any * interim text the engine had not finalized yet. */ stop(): Promise { this.clearRestartTimer(); this.running = false; const recognition = this.recognition; if (!recognition) { return Promise.resolve(this.promoteInterim()); } return new Promise((resolve) => { this.stopResolver = resolve; this.stopTimer = setTimeout(() => this.resolveStop(true), STOP_TIMEOUT_MS); try { recognition.stop(); // late final results still arrive via onresult, then onend } catch { this.resolveStop(true); } }); } /** Immediately terminates the session and discards callbacks. */ abort(): void { this.running = false; this.clearRestartTimer(); if (this.stopTimer) { clearTimeout(this.stopTimer); this.stopTimer = null; } const resolver = this.stopResolver; this.stopResolver = null; this.detachRecognition(true); this.handlers = null; resolver?.(this.promoteInterim()); } dispose(): void { this.abort(); } // --------------------------------------------------------------------------- private startRecognition(): boolean { if (!this.ctor) return false; const recognition = new this.ctor(); recognition.lang = this.lang; recognition.continuous = true; recognition.interimResults = true; recognition.maxAlternatives = 1; recognition.onresult = (event) => this.handleResult(event); recognition.onerror = (event) => this.handleError(event); recognition.onspeechend = () => this.emit((h) => h.onSpeechEnd?.()); recognition.onend = () => this.handleEnd(); this.recognition = recognition; try { recognition.start(); return true; } catch { this.recognition = null; return false; } } private handleResult(event: SpeechRecognitionEventLike): void { // Entries before resultIndex were delivered (and finalized) in earlier events, // so only entries from resultIndex onward are processed: no duplicated words. let interim = ''; for (let i = event.resultIndex; i < event.results.length; i++) { const result = event.results[i]; const text = (result[0]?.transcript ?? '').trim(); if (!text) continue; if (result.isFinal) { this.finalText = this.join(this.finalText, text); } else { interim = this.join(interim, text); } } this.interimText = interim; this.silentRestarts = 0; this.emitTranscript(); } private handleError(event: SpeechRecognitionErrorEventLike): void { switch (event.error) { case 'no-speech': // not fatal: onend decides whether to restart case 'aborted': return; case 'not-allowed': case 'service-not-allowed': this.fail('permission-denied'); return; case 'audio-capture': this.fail('audio-capture'); return; case 'network': this.fail('network'); return; case 'language-not-supported': this.fail('language-not-supported'); return; default: this.fail('unknown'); } } private handleEnd(): void { if (this.stopResolver) { this.resolveStop(false); return; } if (!this.running) return; // The engine ended on its own (pause, timeout, ...): keep what we have and restart. this.detachRecognition(false); this.promoteInterim(); this.emitTranscript(); this.silentRestarts++; if (this.silentRestarts > MAX_SILENT_RESTARTS) { this.fail('no-speech'); return; } this.restartTimer = setTimeout(() => { this.restartTimer = null; if (this.running && !this.startRecognition()) { this.fail('unknown'); } }, RESTART_DELAY_MS); } private fail(kind: SpeechErrorKind): void { const handlers = this.handlers; this.running = false; this.clearRestartTimer(); this.detachRecognition(true); this.emitWith(handlers, (h) => h.onError(kind)); } private resolveStop(abortEngine: boolean): void { if (this.stopTimer) { clearTimeout(this.stopTimer); this.stopTimer = null; } const resolver = this.stopResolver; this.stopResolver = null; const text = this.promoteInterim(); this.detachRecognition(abortEngine); resolver?.(text); } /** Commits interim text to final text (used when a session ends mid-phrase). */ private promoteInterim(): string { if (this.interimText) { this.finalText = this.join(this.finalText, this.interimText); this.interimText = ''; } return this.finalText; } private detachRecognition(abortEngine: boolean): void { const recognition = this.recognition; this.recognition = null; if (!recognition) return; recognition.onresult = null; recognition.onerror = null; recognition.onend = null; recognition.onspeechend = null; if (abortEngine) { try { recognition.abort(); } catch { /* already stopped */ } } } private clearRestartTimer(): void { if (this.restartTimer) { clearTimeout(this.restartTimer); this.restartTimer = null; } } private emitTranscript(): void { const transcript: SpeechTranscript = { final: this.finalText, interim: this.interimText }; this.emit((h) => h.onTranscript(transcript)); } private emit(fn: (handlers: SpeechSessionHandlers) => void): void { this.emitWith(this.handlers, fn); } /** Speech events may fire outside Angular's zone; always hand results back inside it. */ private emitWith( handlers: SpeechSessionHandlers | null, fn: (handlers: SpeechSessionHandlers) => void, ): void { if (!handlers) return; this.ngZone.run(() => fn(handlers)); } private join(a: string, b: string): string { return a && b ? `${a} ${b}` : a || b; } private resolveCtor(): SpeechRecognitionCtor | null { if (typeof window === 'undefined') return null; const w = window as unknown as { SpeechRecognition?: SpeechRecognitionCtor; webkitSpeechRecognition?: SpeechRecognitionCtor; }; return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null; } }