Search code examples
fluttertext-to-speechcountdowntimer

Text to speech for countdown timer


I have a controller that displays the timer for my countdown app.

screenshot

The code to display the timer:

String get timerString {
    duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

I want to add a TTS to speak whenever the timer goes to "3,2,1". Like a countdown TTS. I tried implementing the TTS in the timerString function, but the duration changes too fast for the TTS to speak.

Future _speak(String text) async {
   var result = await flutterTts.speak(text);
 }

Solution

  • Do not await the speak() method. Just trigger it and don't wait it.

    Here is a function that counts down.

    void countdown(FlutterTts tts, int from, Duration delay) async {
      for (var i = from; i > 0; i--) {
        tts.speak(i.toString());
        await Future.delayed(delay);
      }
    }