-
Notifications
You must be signed in to change notification settings - Fork 511
/
main.dart
349 lines (309 loc) · 9.56 KB
/
main.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//
// 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 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:bottom_picker/bottom_picker.dart';
import 'package:porcupine_flutter/porcupine.dart';
import 'package:porcupine_flutter/porcupine_manager.dart';
import 'package:porcupine_flutter/porcupine_error.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
final String accessKey =
"{YOUR_ACCESS_KEY_HERE}"; // AccessKey obtained from Picovoice Console (https://console.picovoice.ai/)
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
late String _language;
late List<String> _keywords;
final Map<String, BuiltInKeyword> _keywordMap = {};
bool isError = false;
String errorMessage = "";
bool isButtonDisabled = false;
bool isProcessing = false;
Color detectionColour = Color(0xff00e5c3);
Color defaultColour = Color(0xfff5fcff);
Color? backgroundColour;
String currentKeyword = "Click to choose a keyword";
PorcupineManager? _porcupineManager;
@override
void initState() {
super.initState();
setState(() {
isButtonDisabled = true;
backgroundColour = defaultColour;
});
WidgetsBinding.instance.addObserver(this);
_initializeKeywordMap();
_loadParams();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.paused) {
await _stopProcessing();
await _porcupineManager?.delete();
_porcupineManager = null;
}
}
Future<void> _loadParams() async {
try {
final paramsString =
await DefaultAssetBundle.of(context).loadString('assets/params.json');
final params = json.decode(paramsString);
String language = params["language"];
List<String> keywords = List<String>.from(params["keywords"]);
if (language == "en") {
for (var builtIn in BuiltInKeyword.values) {
String keyword = builtIn
.toString()
.split(".")
.last
.replaceAll("_", " ")
.toLowerCase();
keywords.add(keyword);
}
}
_language = language;
_keywords = keywords;
} catch (_) {
errorCallback(PorcupineException(
"Could not find `params.json`. Ensure 'prepare_demo.dart' script was run before launching the demo."));
}
}
Future<void> loadNewKeyword(String keyword) async {
setState(() {
isButtonDisabled = true;
});
if (!_keywords.contains(keyword)) {
return;
}
if (isProcessing) {
await _stopProcessing();
}
if (_porcupineManager != null) {
await _porcupineManager?.delete();
_porcupineManager = null;
}
try {
if (_language == "en") {
BuiltInKeyword builtIn = _keywordMap[keyword]!;
_porcupineManager = await PorcupineManager.fromBuiltInKeywords(
accessKey, [builtIn], wakeWordCallback,
errorCallback: errorCallback);
} else {
var platform = (Platform.isAndroid) ? "android" : "ios";
var keywordPath = "assets/keywords/$platform/${keyword}_$platform.ppn";
var modelPath = "assets/models/porcupine_params_$_language.pv";
_porcupineManager = await PorcupineManager.fromKeywordPaths(
accessKey, [keywordPath], wakeWordCallback,
modelPath: modelPath, errorCallback: errorCallback);
}
setState(() {
currentKeyword = keyword;
isError = false;
});
} on PorcupineActivationException {
errorCallback(
PorcupineActivationException("AccessKey activation error."));
} on PorcupineActivationLimitException {
errorCallback(PorcupineActivationLimitException(
"AccessKey reached its device limit."));
} on PorcupineActivationRefusedException {
errorCallback(PorcupineActivationRefusedException("AccessKey refused."));
} on PorcupineActivationThrottledException {
errorCallback(PorcupineActivationThrottledException(
"AccessKey has been throttled."));
} on PorcupineException catch (ex) {
errorCallback(ex);
} finally {
setState(() {
isButtonDisabled = false;
});
}
}
void wakeWordCallback(int keywordIndex) {
if (keywordIndex >= 0) {
setState(() {
backgroundColour = detectionColour;
});
Future.delayed(const Duration(milliseconds: 1000), () {
setState(() {
backgroundColour = defaultColour;
});
});
}
}
void errorCallback(PorcupineException error) {
setState(() {
isError = true;
errorMessage = error.message!;
});
}
Future<void> _startProcessing() async {
setState(() {
isButtonDisabled = true;
});
if (_porcupineManager == null) {
await loadNewKeyword(currentKeyword);
}
try {
await _porcupineManager?.start();
setState(() {
isProcessing = true;
});
} on PorcupineException catch (ex) {
errorCallback(ex);
} finally {
setState(() {
isButtonDisabled = false;
});
}
}
Future<void> _stopProcessing() async {
setState(() {
isButtonDisabled = true;
});
await _porcupineManager?.stop();
setState(() {
isButtonDisabled = false;
isProcessing = false;
});
}
void _toggleProcessing() async {
if (isProcessing) {
await _stopProcessing();
} else {
await _startProcessing();
}
}
void _initializeKeywordMap() {
for (var builtIn in BuiltInKeyword.values) {
String keyword =
builtIn.toString().split(".").last.replaceAll("_", " ").toLowerCase();
_keywordMap[keyword] = builtIn;
}
}
Color picoBlue = Color.fromRGBO(55, 125, 255, 1);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
backgroundColor: backgroundColour,
appBar: AppBar(
title: const Text('Porcupine Demo'),
backgroundColor: picoBlue,
),
body: Column(
children: [
buildPicker(context),
buildStartButton(context),
buildErrorMessage(context),
footer
],
),
),
);
}
buildPicker(BuildContext context) {
return Expanded(
flex: 1,
child: Container(
alignment: Alignment.bottomCenter,
// color: Colors.blue,
child: FractionallySizedBox(
widthFactor: 0.9,
child: OutlinedButton(
child: Text(currentKeyword.toString(),
style: TextStyle(fontSize: 20, color: picoBlue)),
onPressed: () {
showPicker(context);
},
))),
);
}
buildStartButton(BuildContext context) {
final ButtonStyle buttonStyle = ElevatedButton.styleFrom(
backgroundColor: picoBlue,
shape: CircleBorder(),
textStyle: TextStyle(color: Colors.white));
return Expanded(
flex: 2,
child: Container(
child: SizedBox(
width: 150,
height: 150,
child: ElevatedButton(
style: buttonStyle,
onPressed:
(isButtonDisabled || isError) ? null : _toggleProcessing,
child: Text(isProcessing ? "Stop" : "Start",
style: TextStyle(fontSize: 30)),
))),
);
}
buildErrorMessage(BuildContext context) {
return Expanded(
flex: 1,
child: Container(
alignment: Alignment.center,
margin: EdgeInsets.only(left: 20, right: 20),
decoration: !isError
? null
: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(5)),
child: !isError
? null
: Text(
errorMessage,
style: TextStyle(color: Colors.white, fontSize: 20),
)));
}
Widget footer = Expanded(
flex: 1,
child: Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 20),
child: const Text(
"Made in Vancouver, Canada by Picovoice",
style: TextStyle(color: Color(0xff666666)),
)));
showPicker(BuildContext context) {
BottomPicker picker = BottomPicker(
pickerTitle: Text(
"Choose a keyword",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15)),
titleAlignment: Alignment.topCenter,
gradientColors: [
picoBlue, picoBlue
],
items: _keywords.toList().map((x) => Center(
child: Text(x)
)).toList(),
onSubmit: (index) {
loadNewKeyword(_keywords[index]);
},
);
picker.show(_scaffoldKey.currentContext!);
}
}