part of tts;

enum TtsState{playing, stopped, paused, continued}

class TTSController extends GetxController {
  late FlutterTts flutterTts;
  TtsState ttsState = TtsState.stopped;
  late String textToSpeak;

  @override
  void onInit() {
    initTts();
    super.onInit();
  }

  initTts() {
    flutterTts = FlutterTts();
    // 设置语言
    flutterTts.setLanguage('zh-Hans-CN');
    // 设置语速
    flutterTts.setSpeechRate(0.5);
    // 设置音量
    flutterTts.setVolume(1.0);
    // 设置音调
    flutterTts.setPitch(1.0);

    flutterTts.setStartHandler(() {
      ttsState = TtsState.playing;
    });

    flutterTts.setCompletionHandler(() {
      ttsState = TtsState.stopped;
    });

    flutterTts.setPauseHandler(() {
      ttsState = TtsState.paused;
    });

    flutterTts.setContinueHandler(() {
      ttsState = TtsState.continued;
      Console.log('继续');
    });

    flutterTts.setErrorHandler((message) {
      Console.log('error:$message');
      ttsState = TtsState.stopped;
    });
    
    flutterTts.setProgressHandler((text, start, end, word) { 

    });


  }

  Future speak(String text) async {
    textToSpeak = text;
    Console.log(text);
    flutterTts.speak(text);
    Console.log('读文字');
  }

  Future stop() async {
    update();
  }

  Future pause() async {
   if (ttsState == TtsState.playing){
     flutterTts.pause();
     ttsState = TtsState.paused;
   }else if (ttsState == TtsState.paused || ttsState == TtsState.stopped){
     flutterTts.continueHandler!();
   }

  }

  @override
  void onClose() {
    flutterTts.stop();
    super.onClose();
  }



}