You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.8 KiB
103 lines
2.8 KiB
import 'dart:async';
|
|
import 'package:get/get.dart';
|
|
import '../../../data/services/volcano_voice_recognition_service.dart';
|
|
|
|
class AsrTestController extends GetxController {
|
|
final VolcanoVoiceRecognitionService _voiceService = Get.find<VolcanoVoiceRecognitionService>();
|
|
|
|
// 可观察状态
|
|
final isListening = false.obs;
|
|
final errorMessage = ''.obs;
|
|
final isContinuous = true.obs;
|
|
final recognitionResults = <String>[].obs;
|
|
|
|
// 连续识别相关
|
|
StreamSubscription? _recognitionSubscription;
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
|
|
// 监听语音识别服务的状态
|
|
_voiceService.isListening.listen((listening) {
|
|
isListening.value = listening;
|
|
if (!listening) {
|
|
errorMessage.value = '';
|
|
}
|
|
});
|
|
}
|
|
|
|
/// 开始录音
|
|
void startListening() async {
|
|
try {
|
|
errorMessage.value = '';
|
|
|
|
if (isContinuous.value) {
|
|
// 连续识别模式
|
|
final success = await _voiceService.startContinuousRecognition();
|
|
if (!success) {
|
|
errorMessage.value = '无法启动语音识别';
|
|
return;
|
|
}
|
|
|
|
_recognitionSubscription = _voiceService.recognitionStream?.listen(
|
|
(event) {
|
|
switch (event.type) {
|
|
case RecognitionEventType.finalResult:
|
|
if (event.text.isNotEmpty) {
|
|
recognitionResults.add(event.text);
|
|
}
|
|
break;
|
|
case RecognitionEventType.error:
|
|
errorMessage.value = event.error ?? '未知错误';
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
},
|
|
onError: (error) {
|
|
errorMessage.value = error.toString();
|
|
isListening.value = false;
|
|
},
|
|
);
|
|
} else {
|
|
// 一次性识别模式
|
|
final success = await _voiceService.startOneTimeRecognition();
|
|
if (!success) {
|
|
errorMessage.value = '无法启动语音识别';
|
|
return;
|
|
}
|
|
|
|
// 一次性识别模式下,结果会通过服务的recognitionResults获取
|
|
// 在onInit中我们已经监听了isListening状态,当识别完成时会自动更新UI
|
|
}
|
|
} catch (e) {
|
|
errorMessage.value = e.toString();
|
|
isListening.value = false;
|
|
}
|
|
}
|
|
|
|
/// 停止录音
|
|
void stopListening() async {
|
|
try {
|
|
if (isContinuous.value) {
|
|
await _voiceService.stopRecognition();
|
|
await _recognitionSubscription?.cancel();
|
|
_recognitionSubscription = null;
|
|
}
|
|
} catch (e) {
|
|
errorMessage.value = e.toString();
|
|
}
|
|
}
|
|
|
|
/// 清空结果
|
|
void clearResults() {
|
|
recognitionResults.clear();
|
|
}
|
|
|
|
@override
|
|
void onClose() {
|
|
_recognitionSubscription?.cancel();
|
|
super.onClose();
|
|
}
|
|
}
|