flutter_tts.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import 'dart:io';
  2. import 'package:flutter_tts/flutter_tts.dart';
  3. import '../models/index.dart';
  4. import 'log_util.dart';
  5. class FlutterTTSHelper {
  6. // 单例
  7. static final FlutterTTSHelper instance = FlutterTTSHelper._internal();
  8. factory FlutterTTSHelper() => instance;
  9. FlutterTTSHelper._internal();
  10. final FlutterTts _tts = FlutterTts();
  11. TtsState ttsState = TtsState.stopped;
  12. /// 初始化
  13. Future<void> init() async {
  14. await _tts.awaitSpeakCompletion(true);
  15. await _tts.setLanguage("zh-CN"); // 语言
  16. await _tts.setSpeechRate(0.5); // 语速
  17. await _tts.setVolume(0.8); // 声音
  18. _tts.setStartHandler(() {
  19. OLogger.i('FlutterTts start playing ......');
  20. ttsState = TtsState.playing;
  21. });
  22. _tts.setCompletionHandler(() {
  23. OLogger.i('FlutterTts play completion ......');
  24. ttsState = TtsState.stopped;
  25. });
  26. _tts.setCancelHandler(() {
  27. OLogger.i('FlutterTts cancel play ......');
  28. ttsState = TtsState.stopped;
  29. });
  30. _tts.setPauseHandler(() {
  31. OLogger.i('FlutterTts paused play ......');
  32. ttsState = TtsState.paused;
  33. });
  34. _tts.setContinueHandler(() {
  35. OLogger.i('FlutterTts Continue play ......');
  36. ttsState = TtsState.continued;
  37. });
  38. _tts.setErrorHandler((msg) {
  39. OLogger.e('FlutterTts error $msg');
  40. ttsState = TtsState.stopped;
  41. });
  42. OLogger.i('TTS init completed!');
  43. }
  44. /// 当前状态
  45. TtsState currentState() {
  46. return ttsState;
  47. }
  48. /// 开始说话
  49. Future<void> speak(String msg) async {
  50. if (ttsState != TtsState.stopped) {
  51. await stop();
  52. }
  53. if (Platform.isIOS) {
  54. await _tts.setSharedInstance(true);
  55. await _tts.setIosAudioCategory(IosTextToSpeechAudioCategory.ambientSolo, [IosTextToSpeechAudioCategoryOptions.defaultToSpeaker]);
  56. }
  57. final result = await _tts.speak(msg);
  58. OLogger.i('用户指令 TTS speak $result');
  59. }
  60. /// 结束说话
  61. Future<void> stop() async {
  62. final result = await _tts.stop();
  63. OLogger.i('用户指令 TTS stoped $result');
  64. }
  65. }