-
Notifications
You must be signed in to change notification settings - Fork 499
/
porcupine_manager.tsx
209 lines (191 loc) · 6.73 KB
/
porcupine_manager.tsx
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//
// Copyright 2020-2023 Picovoice Inc.
//
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
import {
VoiceProcessor,
VoiceProcessorError,
VoiceProcessorErrorListener,
VoiceProcessorFrameListener,
} from '@picovoice/react-native-voice-processor';
import Porcupine from './porcupine';
import * as PorcupineErrors from './porcupine_errors';
import type BuiltInKeywords from './builtin_keywords';
export type DetectionCallback = (keywordIndex: number) => void;
export type ProcessErrorCallback = (
error: PorcupineErrors.PorcupineError
) => void;
class PorcupineManager {
private readonly _voiceProcessor: VoiceProcessor;
private readonly _errorListener: VoiceProcessorErrorListener;
private readonly _frameListener: VoiceProcessorFrameListener;
private _porcupine: Porcupine | null;
private _isListening: boolean = false;
/**
* Static creator for initializing a Porcupine Manager from built-in keywords
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param keywords List of keywords (phrases) for detection. The list of available (default) keywords can be retrieved.
* using `Porcupine.KEYWORDS`. If `keyword_paths` is set then this argument will be ignored.
* @param detectionCallback A callback for when Porcupine detects the specified keywords.
* @param processErrorCallback A callback for when Porcupine process function triggers an error.
* @param modelPath Path to the file containing model parameters. If not set it will be set to the default location.
* @param sensitivities sensitivities for each keyword model. A higher sensitivity reduces miss rate
* at the cost of potentially higher false alarm rate. Sensitivity should be a floating-point number within
* [0, 1].
* @returns An instance of the Porcupine Manager.
*/
public static async fromBuiltInKeywords(
accessKey: string,
keywords: BuiltInKeywords[],
detectionCallback: DetectionCallback,
processErrorCallback?: ProcessErrorCallback,
modelPath?: string,
sensitivities?: number[]
) {
let porcupine = await Porcupine.fromBuiltInKeywords(
accessKey,
keywords,
modelPath,
sensitivities
);
return new PorcupineManager(
porcupine,
detectionCallback,
processErrorCallback
);
}
/**
* Static creator for initializing a Porcupine Manager from paths to custom keywords.
*
* @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
* @param keywordPaths Absolute paths to keyword model files.
* @param detectionCallback A callback for when Porcupine detects the specified keywords.
* @param processErrorCallback A callback for when Porcupine process function triggers an error.
* @param modelPath Path to the file containing model parameters. If not set it will be set to the default location.
* @param sensitivities sensitivities for each keyword model. A higher sensitivity reduces miss rate
* at the cost of potentially higher false alarm rate. Sensitivity should be a floating-point number within
* [0, 1].
* @returns An instance of the Porcupine Manager.
*/
public static async fromKeywordPaths(
accessKey: string,
keywordPaths: string[],
detectionCallback: DetectionCallback,
processErrorCallback?: ProcessErrorCallback,
modelPath?: string,
sensitivities?: number[]
) {
let porcupine = await Porcupine.fromKeywordPaths(
accessKey,
keywordPaths,
modelPath,
sensitivities
);
return new PorcupineManager(
porcupine,
detectionCallback,
processErrorCallback
);
}
private constructor(
porcupine: Porcupine,
detectionCallback: DetectionCallback,
processErrorCallback?: ProcessErrorCallback
) {
this._porcupine = porcupine;
this._voiceProcessor = VoiceProcessor.instance;
this._frameListener = async (frame: number[]) => {
if (this._porcupine === null || !this._isListening) {
return;
}
try {
let keywordIndex: number = await this._porcupine.process(frame);
if (keywordIndex >= 0) {
detectionCallback(keywordIndex);
}
} catch (e) {
if (processErrorCallback) {
processErrorCallback(e as PorcupineErrors.PorcupineError);
} else {
console.error(e);
}
}
};
this._errorListener = (error: VoiceProcessorError) => {
if (processErrorCallback) {
processErrorCallback(new PorcupineErrors.PorcupineError(error.message));
} else {
console.error(error);
}
};
}
/**
* Opens audio input stream and sends audio frames to Porcupine
*/
public async start(): Promise<void> {
if (this._isListening) {
return;
}
if (this._porcupine === null) {
throw new PorcupineErrors.PorcupineInvalidStateError(
'Cannot start Porcupine - resources have already been released'
);
}
if (await this._voiceProcessor.hasRecordAudioPermission()) {
this._voiceProcessor.addFrameListener(this._frameListener);
this._voiceProcessor.addErrorListener(this._errorListener);
try {
await this._voiceProcessor.start(
this._porcupine.frameLength,
this._porcupine.sampleRate
);
} catch (e: any) {
throw new PorcupineErrors.PorcupineRuntimeError(
`Failed to start audio recording: ${e.message}`
);
}
} else {
throw new PorcupineErrors.PorcupineRuntimeError(
'User did not give permission to record audio.'
);
}
this._isListening = true;
}
/**
* Closes audio stream
*/
public async stop(): Promise<void> {
if (!this._isListening) {
return;
}
this._voiceProcessor.removeErrorListener(this._errorListener);
this._voiceProcessor.removeFrameListener(this._frameListener);
if (this._voiceProcessor.numFrameListeners === 0) {
try {
await this._voiceProcessor.stop();
} catch (e: any) {
throw new PorcupineErrors.PorcupineRuntimeError(
`Failed to stop audio recording: ${e.message}`
);
}
}
this._isListening = false;
}
/**
* Releases resources and listeners
*/
delete() {
if (this._porcupine !== null) {
this._porcupine.delete();
this._porcupine = null;
}
}
}
export default PorcupineManager;