0fa4e405
吴启风
feat: 将语音评测从先声迁移至驰声
|
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
|
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:audio_session/audio_session.dart';
import 'package:chivox_aiengine/chivox_aiengine.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import '../core/app_consts.dart';
/// 将驰声 Flutter SDK 适配为原评测桥接的事件协议,业务页面无需感知 SDK 差异。
class ChivoxEvaluationChannel {
ChivoxAiengine? _engine;
Future<void>? _initializing;
Future<dynamic> Function(MethodCall)? _methodCallHandler;
int _sessionId = 0;
bool _active = false;
bool _stopping = false;
bool _stopNotified = false;
String? _recordFilePath;
void setMethodCallHandler(
Future<dynamic> Function(MethodCall)? methodCallHandler) {
_methodCallHandler = methodCallHandler;
}
Future<T?> invokeMethod<T>(String method, [dynamic arguments]) async {
final params = _asStringMap(arguments);
switch (method) {
case 'initVoiceSdk':
await _initialize();
break;
case 'startVoice':
await _startInnerRecorder(params);
break;
case 'startLocalVoice':
await _evaluateWaveFile(params);
break;
case 'stopVoice':
await _stop();
break;
case 'cancelVoice':
await _cancel(notify: true);
break;
default:
throw MissingPluginException('Unsupported evaluation method: $method');
}
return null;
}
Future<void> dispose() async {
_sessionId++;
await _cancel(notify: false);
final engine = _engine;
_engine = null;
_initializing = null;
await engine?.destroy();
_methodCallHandler = null;
}
Future<void> _initialize() {
if (_engine != null) return Future.value();
return _initializing ??= _createEngine().catchError((Object error) {
_initializing = null;
throw error;
});
}
Future<void> _createEngine() async {
final supportDirectory = await getApplicationSupportDirectory();
final resourceDirectory = Directory('${supportDirectory.path}/chivox');
if (!await resourceDirectory.exists()) {
await resourceDirectory.create(recursive: true);
}
final provisionPath = await _copyAssetIfNeeded(
'assets/chivox/aiengine.provision',
'${resourceDirectory.path}/aiengine.provision',
);
final vadPath = await _copyAssetIfNeeded(
'assets/chivox/vad.0.13.bin',
'${resourceDirectory.path}/vad.0.13.bin',
);
final config = jsonEncode({
'appKey': AppConsts.chivoxAppKey,
'secretKey': AppConsts.chivoxSecretKey,
'provision': provisionPath,
'vad': {
'enable': 1,
'res': vadPath,
'speechLowSeek': 125,
'sampleRate': 16000,
'strip': 0,
},
'cloud': {'enable': 1},
});
_engine = await ChivoxAiengine.create(config);
}
Future<void> _startInnerRecorder(Map<String, String> params) async {
await _prepareAudioSession();
await _startEvaluation(
params,
audioSourceBuilder: (recordFilePath) => {
'srcType': 'innerRecorder',
'innerRecorderParam': {
'channel': 1,
'sampleBytes': 2,
'sampleRate': 16000,
'saveFile': recordFilePath,
},
},
);
}
Future<void> _evaluateWaveFile(Map<String, String> params) async {
final wavePath = params['voicePath'] ?? '';
if (wavePath.isEmpty || !await File(wavePath).exists()) {
await _emit('voiceFail', {
'code': -1,
'message': '录音文件不存在',
});
return;
}
await _startEvaluation(
params,
fallbackRecordPath: wavePath,
audioSourceBuilder: (_) => {'srcType': 'outerFeed'},
afterStarted: (sessionId) async {
final pcmBytes = await _readWavePcm(File(wavePath));
const chunkSize = 8192;
for (var offset = 0;
offset < pcmBytes.length && _isActiveSession(sessionId);
offset += chunkSize) {
final end = (offset + chunkSize).clamp(0, pcmBytes.length);
final chunk = Uint8List.sublistView(pcmBytes, offset, end);
await _engine?.feed(chunk, chunk.length);
}
if (_isActiveSession(sessionId)) await _stop();
},
);
}
Future<void> _startEvaluation(
Map<String, String> params, {
required Map<String, dynamic> Function(String recordFilePath)
audioSourceBuilder,
String? fallbackRecordPath,
Future<void> Function(int sessionId)? afterStarted,
}) async {
try {
await _initialize();
if (_active) await _cancel(notify: false);
final text = _normalizeReferenceText(params['word'] ?? '');
if (text.isEmpty) {
throw const FormatException('评测文本不能为空');
}
final sessionId = ++_sessionId;
_active = true;
_stopping = false;
_stopNotified = false;
_recordFilePath = fallbackRecordPath ?? await _newRecordFilePath();
final request = jsonEncode({
'coreProvideType': 'cloud',
'vad': {
'vadEnable': fallbackRecordPath == null ? 1 : 0,
'refDuration': 3,
'speechLowSeek': 125,
},
'app': {'userId': params['userId'] ?? 'guest'},
'audio': {
'audioType': 'wav',
'channel': 1,
'sampleBytes': 2,
'sampleRate': 16000,
'compress': 'speex',
},
'request': {
'coreType': 'en.sent.score',
'refText': text,
'rank': 100,
'attachAudioUrl': 0,
'result': {
'details': {'gop_adjust': 0}
},
},
});
final listener = ChivoxAiengineResultListener(
onEvalResult: (result) => _handleResult(sessionId, text, result),
onError: (result) => unawaited(_handleError(sessionId, result)),
onVad: (result) => _handleVad(sessionId, result),
);
await _engine!.start(
audioSourceBuilder(_recordFilePath!),
request,
listener,
);
if (!_isActiveSession(sessionId)) return;
await _emit('voiceStart', null);
await afterStarted?.call(sessionId);
} catch (error) {
_active = false;
_stopping = false;
try {
await _engine?.cancel();
} catch (_) {}
await _emit('voiceFail', {
'code': error is PlatformException ? error.code : -1,
'message': error.toString(),
});
}
}
void _handleResult(
int sessionId, String referenceText, ChivoxAiengineResult result) {
if (!_isActiveSession(sessionId)) return;
try {
final raw = jsonDecode(result.text ?? '{}') as Map<String, dynamic>;
final resultJson = raw['result'] as Map<String, dynamic>? ?? const {};
final detailsJson = resultJson['details'] as List<dynamic>? ?? const [];
final details = detailsJson
.whereType<Map>()
.map((detail) {
return {
'char': detail['char']?.toString() ?? '',
'score': _asScore(detail['score']),
};
})
.where((detail) => (detail['char'] as String).isNotEmpty)
.toList();
_active = false;
_stopping = false;
unawaited(_emit('voiceResult', {
'result': {
'overall': _asScore(resultJson['overall']),
'details': details,
'refText': referenceText,
},
'audioUrl': result.recFilePath ?? _recordFilePath ?? '',
}));
} catch (error) {
unawaited(_handleError(sessionId, null, error: error));
}
}
Future<void> _handleError(
int sessionId,
ChivoxAiengineResult? result, {
Object? error,
}) async {
if (!_isActiveSession(sessionId)) return;
_active = false;
_stopping = false;
try {
await _engine?.cancel();
} catch (_) {}
var code = -1;
var message = error?.toString() ?? result?.text ?? '评测失败';
try {
final errorJson = jsonDecode(result?.text ?? '') as Map<String, dynamic>;
code = _asScore(errorJson['errId']);
message = errorJson['error']?.toString() ?? message;
} catch (_) {}
await _emit('voiceFail', {'code': code, 'message': message});
}
void _handleVad(int sessionId, ChivoxAiengineResult result) {
if (!_isActiveSession(sessionId) || _stopping) return;
try {
final vad = jsonDecode(result.text ?? '{}') as Map<String, dynamic>;
if (_asScore(vad['vad_status']) == 2) unawaited(_stop());
} catch (_) {}
}
Future<void> _stop() async {
if (!_active || _stopping) return;
_stopping = true;
try {
await _engine?.stop();
if (!_stopNotified) {
_stopNotified = true;
await _emit('voiceEnd', null);
}
} catch (error) {
_active = false;
_stopping = false;
_sessionId++;
try {
await _engine?.cancel();
} catch (_) {}
await _emit('voiceFail', {
'code': error is PlatformException ? error.code : -1,
'message': error.toString(),
});
}
}
Future<void> _cancel({required bool notify}) async {
final wasActive = _active;
_active = false;
_stopping = false;
_sessionId++;
try {
await _engine?.cancel();
} catch (_) {}
if (notify && wasActive) await _emit('voiceCancel', null);
}
bool _isActiveSession(int sessionId) => _active && sessionId == _sessionId;
Future<void> _prepareAudioSession() async {
final session = await AudioSession.instance;
await session.configure(AudioSessionConfiguration(
avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions:
AVAudioSessionCategoryOptions.defaultToSpeaker |
AVAudioSessionCategoryOptions.allowBluetooth,
avAudioSessionMode: AVAudioSessionMode.spokenAudio,
androidAudioAttributes: const AndroidAudioAttributes(
contentType: AndroidAudioContentType.speech,
usage: AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
await session.setActive(true);
}
Future<String> _newRecordFilePath() async {
final tempDirectory = await getTemporaryDirectory();
final directory = Directory('${tempDirectory.path}/chivox_records');
if (!await directory.exists()) await directory.create(recursive: true);
return '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.wav';
}
Future<String> _copyAssetIfNeeded(String assetPath, String targetPath) async {
final data = await rootBundle.load(assetPath);
final file = File(targetPath);
if (!await file.exists() || await file.length() != data.lengthInBytes) {
await file.writeAsBytes(data.buffer.asUint8List(), flush: true);
}
return file.path;
}
Future<Uint8List> _readWavePcm(File file) async {
final bytes = await file.readAsBytes();
if (bytes.length < 12 || ascii.decode(bytes.sublist(0, 4)) != 'RIFF') {
return bytes;
}
var offset = 12;
final byteData = ByteData.sublistView(bytes);
while (offset + 8 <= bytes.length) {
final chunkName =
ascii.decode(bytes.sublist(offset, offset + 4), allowInvalid: true);
final chunkLength = byteData.getUint32(offset + 4, Endian.little);
final dataStart = offset + 8;
final dataEnd = (dataStart + chunkLength).clamp(0, bytes.length);
if (chunkName == 'data') {
return Uint8List.sublistView(bytes, dataStart, dataEnd);
}
offset = dataEnd + (chunkLength.isOdd ? 1 : 0);
}
throw const FormatException('无效的 WAV 文件');
}
Future<void> _emit(String method, dynamic arguments) async {
await _methodCallHandler?.call(MethodCall(method, arguments));
}
Map<String, String> _asStringMap(dynamic arguments) {
if (arguments is! Map) return const {};
return arguments
.map((key, value) => MapEntry(key.toString(), value?.toString() ?? ''));
}
int _asScore(dynamic value) {
if (value is num) return value.round();
return double.tryParse(value?.toString() ?? '')?.round() ?? 0;
}
String _normalizeReferenceText(String text) => text
.trim()
.replaceAll('’', "'")
.replaceAll('‘', "'")
.replaceAll('“', '"')
.replaceAll('”', '"')
.replaceAll(',', ',')
.replaceAll('。', '.')
.replaceAll('?', '?')
.replaceAll('!', '!');
}
|