|
| 1 | +import { Injectable } from '@furystack/inject' |
| 2 | +import { Lock } from 'semaphore-async-await' |
| 3 | + |
| 4 | +type SpeechRecognitionEvent = { |
| 5 | + results: SpeechRecognitionResultList |
| 6 | +} |
| 7 | + |
| 8 | +type SpeechRecognitionResultList = { |
| 9 | + [index: number]: SpeechRecognitionResult |
| 10 | + length: number |
| 11 | +} |
| 12 | + |
| 13 | +type SpeechRecognitionError = { |
| 14 | + error: string |
| 15 | + message: string |
| 16 | +} |
| 17 | + |
| 18 | +declare class webkitSpeechRecognition { |
| 19 | + continuous: boolean |
| 20 | + interimResults: boolean |
| 21 | + lang: string |
| 22 | + public start(): void |
| 23 | + public stop(): void |
| 24 | + public onresult: (event: SpeechRecognitionEvent) => void |
| 25 | + public onerror: (event: SpeechRecognitionError) => void |
| 26 | + public onend: () => void |
| 27 | +} |
| 28 | + |
| 29 | +@Injectable({ lifetime: 'singleton' }) |
| 30 | +export class SpeechRecognitionService { |
| 31 | + public lock = new Lock() |
| 32 | + |
| 33 | + public async recognizeSpeech(): Promise<string> { |
| 34 | + try { |
| 35 | + await this.lock.acquire() |
| 36 | + |
| 37 | + const speechRecognition = new webkitSpeechRecognition() |
| 38 | + |
| 39 | + return new Promise((resolve, reject) => { |
| 40 | + if (!speechRecognition) { |
| 41 | + reject(new Error('Speech recognition is not supported in this browser.')) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + speechRecognition.lang = 'hu-HU' |
| 46 | + |
| 47 | + speechRecognition.onresult = (event) => { |
| 48 | + if (event.results.length > 0) { |
| 49 | + resolve(event.results[0][0].transcript) |
| 50 | + } else { |
| 51 | + reject(new Error('No speech recognized.')) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + speechRecognition.onerror = (event: SpeechRecognitionError) => { |
| 56 | + reject(new Error(`Speech recognition error: ${event.error}`)) |
| 57 | + } |
| 58 | + |
| 59 | + speechRecognition.onend = () => { |
| 60 | + console.log('Speech recognition ended.') |
| 61 | + } |
| 62 | + |
| 63 | + speechRecognition.start() |
| 64 | + }) |
| 65 | + } finally { |
| 66 | + this.lock.release() |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments