Translate-Flutter/lib/global/speech_to_text_manager.dart
fengshengxiong 70d663706c 第一版
2024-07-12 11:26:44 +08:00

86 lines
2.5 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Author: fengshengxiong
// Date: 2024/5/8
// Description: 语音转文本
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:trans_lark/widget/base_easyloading.dart';
class SpeechToTextManager {
static final SpeechToTextManager _instance = SpeechToTextManager._();
factory SpeechToTextManager() {
return _instance;
}
SpeechToTextManager._();
final _speechToText = SpeechToText();
var hasSpeech = false;
var isListening = false.obs;
Future<void> initSpeech() async {
try {
BaseEasyLoading.loading();
hasSpeech = await _speechToText.initialize(
onStatus: _statusListener,
onError: _errorListener,
);
BaseEasyLoading.dismiss();
_speechToText.statusListener ??= _statusListener;
_speechToText.errorListener ??= _errorListener;
} catch (e) {
debugPrint('Speech recognition failed: ${e.toString()}');
}
}
void _statusListener(String status) {
debugPrint('状态:$status');
if (status == 'listening') {
isListening.value = true;
} else {
isListening.value = false;
}
}
void _errorListener(SpeechRecognitionError error) {
debugPrint('Received error status: $error, listening: ${_speechToText.isListening}');
BaseEasyLoading.toast('Speech recognition failed: ${error.errorMsg}');
}
Future<void> startListening(String localeId, SpeechResultListener onResult) async {
BaseEasyLoading.loading();
try {
await _speechToText.listen(
onResult: onResult,
localeId: localeId,
listenFor: const Duration(minutes: 30),
pauseFor: const Duration(minutes: 3),
listenOptions: SpeechListenOptions(
cancelOnError: true,
autoPunctuation: true,
listenMode: ListenMode.dictation,
),
);
BaseEasyLoading.dismiss();
} catch (e) {
if (e.runtimeType == ListenFailedException) {
debugPrint('speechToText.listen${(e as ListenFailedException).message}');
} else {
debugPrint('speechToText.listen${e.toString()}');
}
BaseEasyLoading.toast('The current language does not support speech recognition');
}
}
Future<void> stopListening() async {
if (isListening.value) {
BaseEasyLoading.loading();
await _speechToText.stop();
BaseEasyLoading.dismiss();
}
}
}