/
SpeechRecognizer.ts
53 lines (45 loc) · 1.87 KB
/
SpeechRecognizer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Strings } from '../../System/Strings';
import { ISpeechCommand } from './ISpeechCommand';
import { ISpeechRecognition, SpeechRecognitionEvent, SpeechRecognitionEvents } from './ISpeechRecognition';
import { ISpeechRecognizer } from './ISpeechRecognizer';
declare global {
interface Window {
webkitSpeechRecognition?: { new(): ISpeechRecognition }
}
}
export class SpeechRecognizer implements ISpeechRecognizer {
private speechRecognition: ISpeechRecognition;
constructor(
speechRecognition: ISpeechRecognition | null = window && window.webkitSpeechRecognition ?
new window.webkitSpeechRecognition() : null
) {
if (!speechRecognition) {
throw new Error('No speech recognition service is available.');
} else {
this.speechRecognition = speechRecognition;
}
this.speechRecognition.continuous = false;
this.speechRecognition.interimResults = false;
}
public async Listen(): Promise<string> {
return new Promise((resolve) => {
let result = Strings.Empty;
const resultEvent = (e: SpeechRecognitionEvent) => { result = Array.from(e.results)[0][0].transcript; };
const endEvent = () => {
this.speechRecognition.removeEventListener(SpeechRecognitionEvents.Result, resultEvent);
this.speechRecognition.removeEventListener(SpeechRecognitionEvents.End, endEvent);
resolve(result);
};
this.speechRecognition.addEventListener(SpeechRecognitionEvents.Result, resultEvent);
this.speechRecognition.addEventListener(SpeechRecognitionEvents.End, endEvent);
this.speechRecognition.start();
});
}
public async HandleSpeechCommands(commands: ISpeechCommand[], until: () => boolean): Promise<void> {
do {
const transcript = await this.Listen();
const command = commands.find(c => c.Condition(transcript));
await command?.Action();
} while (!until());
}
}