-
Notifications
You must be signed in to change notification settings - Fork 501
/
porcupine.dart
235 lines (211 loc) · 8.02 KB
/
porcupine.dart
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//
// Copyright 2020-2024 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 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:porcupine_flutter/porcupine_error.dart';
/// BuiltInKeywords
enum BuiltInKeyword {
// ignore:constant_identifier_names
ALEXA,
// ignore:constant_identifier_names
AMERICANO,
// ignore:constant_identifier_names
BLUEBERRY,
// ignore:constant_identifier_names
BUMBLEBEE,
// ignore:constant_identifier_names
COMPUTER,
// ignore:constant_identifier_names
GRAPEFRUIT,
// ignore:constant_identifier_names
GRASSHOPPER,
// ignore:constant_identifier_names
HEY_GOOGLE,
// ignore:constant_identifier_names
HEY_SIRI,
// ignore:constant_identifier_names
JARVIS,
// ignore:constant_identifier_names
OK_GOOGLE,
// ignore:constant_identifier_names
PICOVOICE,
// ignore:constant_identifier_names
PORCUPINE,
// ignore:constant_identifier_names
TERMINATOR
}
enum _NativeFunctions {
// ignore:constant_identifier_names
FROM_BUILTIN_KEYWORDS,
// ignore:constant_identifier_names
FROM_KEYWORD_PATHS,
// ignore:constant_identifier_names
PROCESS,
// ignore:constant_identifier_names
DELETE
}
class Porcupine {
static final MethodChannel _channel = MethodChannel("porcupine");
String? _handle;
final int _frameLength;
final int _sampleRate;
final String _version;
/// Porcupine version string
String get version => _version;
/// The number of audio samples per frame required by Porcupine
int get frameLength => _frameLength;
/// The audio sample rate required by Porcupine
int get sampleRate => _sampleRate;
/// Static creator for initializing Porcupine from a selection of built-in keywords
///
/// [accessKey] AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
///
/// [keywords] is a List of (phrases) for detection. The list of available
/// keywords can be retrieved using [BuiltInKeyword] enum.
///
/// [modelPath] is a path to the file containing model parameters. If not set
/// it will be set to the default location.
///
/// [sensitivities] sensitivities for each keywords 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 and 1.
///
/// Throws a `PorcupineException` if not initialized correctly
///
/// returns an instance of the wake word engine
static Future<Porcupine> fromBuiltInKeywords(
String accessKey, List<BuiltInKeyword> keywords,
{String? modelPath, List<double>? sensitivities}) async {
if (modelPath != null) {
modelPath = await _tryExtractFlutterAsset(modelPath);
}
List<String> keywordValues = List.empty(growable: true);
for (var keyword in keywords) {
keywordValues.add(keyword
.toString()
.split('.')
.last
.replaceAll('_', ' ')
.toLowerCase());
}
try {
Map<String, dynamic> result = Map<String, dynamic>.from(
await _channel.invokeMethod(_NativeFunctions.FROM_BUILTIN_KEYWORDS.name, {
'accessKey': accessKey,
'modelPath': modelPath,
'keywords': keywordValues,
'sensitivities': sensitivities
}));
return Porcupine._(result['handle'], result['frameLength'],
result['sampleRate'], result['version']);
} on PlatformException catch (error) {
throw porcupineStatusToException(error.code, error.message);
} on Exception catch (error) {
throw porcupineStatusToException("PorcupineException", error.toString());
}
}
/// Static creator for initializing Porcupine from a list of paths to custom keyword files
///
/// [accessKey] AccessKey obtained from Picovoice Console (https://console.picovoice.ai/).
///
/// [keywordPaths] A List of absolute paths to keyword model files.
///
/// [modelPath] is a path to the file containing model parameters. If not set
/// it will be set to the default location.
///
/// [sensitivities] sensitivities for each keywords 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 and 1.
///
/// Throws a `PorcupineException` if not initialized correctly
///
/// returns an instance of the wake word engine
static Future<Porcupine> fromKeywordPaths(
String accessKey, List<String> keywordPaths,
{String? modelPath, List<double>? sensitivities}) async {
if (modelPath != null) {
modelPath = await _tryExtractFlutterAsset(modelPath);
}
for (var i = 0; i < keywordPaths.length; i++) {
keywordPaths[i] = await _tryExtractFlutterAsset(keywordPaths[i]);
}
try {
Map<String, dynamic> result = Map<String, dynamic>.from(
await _channel.invokeMethod(_NativeFunctions.FROM_KEYWORD_PATHS.name, {
'accessKey': accessKey,
'modelPath': modelPath,
'keywordPaths': keywordPaths,
'sensitivities': sensitivities
}));
return Porcupine._(result['handle'], result['frameLength'],
result['sampleRate'], result['version']);
} on PlatformException catch (error) {
throw porcupineStatusToException(error.code, error.message);
} on Exception catch (error) {
throw porcupineStatusToException("PorcupineException", error.toString());
}
}
// private constructor
Porcupine._(this._handle, this._frameLength, this._sampleRate, this._version);
/// Process a frame of audio with the wake word engine.
///
/// [frame] is a frame of frame of audio samples to be assessed by Porcupine. The required audio format is found by
/// calling `.sampleRate` to get the required sample rate and `.frameLength` to get the required frame size.
/// Audio must be single-channel and 16-bit linearly-encoded.
///
/// Index of the detected keyword, or -1 if no detection occurred
Future<int> process(List<int>? frame) async {
try {
int keywordIndex = await _channel
.invokeMethod(_NativeFunctions.PROCESS.name, {'handle': _handle, 'frame': frame});
return keywordIndex;
} on PlatformException catch (error) {
throw porcupineStatusToException(error.code, error.message);
} on Exception catch (error) {
throw porcupineStatusToException("PorcupineException", error.toString());
}
}
/// Frees memory that was allocated for Porcupine
Future<void> delete() async {
if (_handle != null) {
await _channel.invokeMethod(_NativeFunctions.DELETE.name, {'handle': _handle});
_handle = null;
}
}
static Future<String> _tryExtractFlutterAsset(String filePath) async {
ByteData data;
try {
data = await rootBundle.load(filePath);
} catch (_) {
// In flutter, a resource can be added through flutter's assets directory
// or natively (res for android; bundle for iOS). We try to extract
// a resource in flutter's assets directory and if it fails, try to load
// the resource using native modules.
return filePath;
}
try {
String resourceDirectory =
(await getApplicationDocumentsDirectory()).path;
String outputPath = '$resourceDirectory/$filePath';
File outputFile = File(outputPath);
final buffer = data.buffer;
await outputFile.create(recursive: true);
await outputFile.writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
return outputPath;
} catch (_) {
throw porcupineStatusToException(
"PorcupineIOException", "failed to extract '$filePath'");
}
}
}