import 'dart:io'; import 'package:flutter_tts/flutter_tts.dart'; import '../models/index.dart'; import 'log_util.dart'; class FlutterTTSHelper { // 单例 static final FlutterTTSHelper instance = FlutterTTSHelper._internal(); factory FlutterTTSHelper() => instance; FlutterTTSHelper._internal(); final FlutterTts _tts = FlutterTts(); TtsState ttsState = TtsState.stopped; /// 初始化 Future init() async { await _tts.awaitSpeakCompletion(true); await _tts.setLanguage("zh-CN"); // 语言 await _tts.setSpeechRate(0.5); // 语速 await _tts.setVolume(0.8); // 声音 _tts.setStartHandler(() { OLogger.i('FlutterTts start playing ......'); ttsState = TtsState.playing; }); _tts.setCompletionHandler(() { OLogger.i('FlutterTts play completion ......'); ttsState = TtsState.stopped; }); _tts.setCancelHandler(() { OLogger.i('FlutterTts cancel play ......'); ttsState = TtsState.stopped; }); _tts.setPauseHandler(() { OLogger.i('FlutterTts paused play ......'); ttsState = TtsState.paused; }); _tts.setContinueHandler(() { OLogger.i('FlutterTts Continue play ......'); ttsState = TtsState.continued; }); _tts.setErrorHandler((msg) { OLogger.e('FlutterTts error $msg'); ttsState = TtsState.stopped; }); OLogger.i('TTS init completed!'); } /// 当前状态 TtsState currentState() { return ttsState; } /// 开始说话 Future speak(String msg) async { if (ttsState != TtsState.stopped) { await stop(); } if (Platform.isIOS) { await _tts.setSharedInstance(true); await _tts.setIosAudioCategory(IosTextToSpeechAudioCategory.ambientSolo, [IosTextToSpeechAudioCategoryOptions.defaultToSpeaker]); } final result = await _tts.speak(msg); OLogger.i('用户指令 TTS speak $result'); } /// 结束说话 Future stop() async { final result = await _tts.stop(); OLogger.i('用户指令 TTS stoped $result'); } }