Text-to-Speech Flutter Plugin (Android & iOS)

Hello guys, in this post we are going to learn How to do Text to speech in flutter?

By using text-to-speech Flutter plugin to read aloud text

In this example we have the Text in the screen while press the play button it will read the text and speak out

 

pubspec.yaml dependencies

add  flutter_tts plugin to application in pubspec.yaml file under dependencies

dependencies:
  flutter_tts: ^0.8.6

 

Let's create app

Create Application with StatefulWidget

add below package in the widget screen

import 'package:flutter_tts/flutter_tts.dart'; in the widget

Now let's define the required fileds

//Text which is going to speak 
String text="The first version of Flutter was known as codename 'Sky' and ran on the Android operating system. It was unveiled at the 2015 Dart developer summit, with the stated intent of being able to render consistently at 120 frames per second.[6] During the keynote of Google Developer Days in Shanghai, Google announced Flutter Release Preview 2 which is the last big release before Flutter 1.0. On December 4, 2018, Flutter 1.0 was released at the Flutter Live event, denoting the first 'stable' version of the Framework.[7] On December 11, 2019, Flutter 1.12 was released at the Flutter Interactive event, it was announced that Flutter was the first UI platform designed for ambient computing";
 
 // Player Status
 bool isPlaying = false;
 
 // Flutter TTS object
 FlutterTts _flutterTts;

 

Now initialize TTS object

initializeTts() {
    _flutterTts = FlutterTts();

    _flutterTts.setStartHandler(() {
      setState(() {
        isPlaying = true;
      });
    });

    _flutterTts.setCompletionHandler(() {
      setState(() {
        isPlaying = false;
      });
    });

    _flutterTts.setErrorHandler((err) {
      setState(() {
        print("error occurred: " + err);
        isPlaying = false;
      });
    });
  }

 

In the above we are hanldling the each stage of playing, completed, error while playing
  

  Now its time to play the given text on button press

Future _speak(String text) async {
    if (text != null && text.isNotEmpty) {
      var result = await _flutterTts.speak(text);
      if (result == 1)
        setState(() {
          isPlaying = true;
        });
    }
  }

 

For stop the player

Future _stop() async {
    var result = await _flutterTts.stop();
    if (result == 1)
      setState(() {
        isPlaying = false;
      });
  }

 

Complete code

import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
void main() => runApp(TTSExampleWidget());



class TTSExampleWidget extends StatefulWidget {



  @override
  _TTSExampleWidgetState createState() => _TTSExampleWidgetState();
}

class _TTSExampleWidgetState extends State {

  String text="The first version of Flutter was known as codename 'Sky' and ran on the Android operating system. It was unveiled at the 2015 Dart developer summit, with the stated intent of being able to render consistently at 120 frames per second.[6] During the keynote of Google Developer Days in Shanghai, Google announced Flutter Release Preview 2 which is the last big release before Flutter 1.0. On December 4, 2018, Flutter 1.0 was released at the Flutter Live event, denoting the first 'stable' version of the Framework.[7] On December 11, 2019, Flutter 1.12 was released at the Flutter Interactive event, it was announced that Flutter was the first UI platform designed for ambient computing";
  bool isPlaying = false;
  FlutterTts _flutterTts;

  @override
  void initState() {
    super.initState();
    initializeTts();
  }

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(

          title: Text("Text To Speach"),
          backgroundColor: Colors.pink,
          centerTitle: true,
        ),
        body: Padding(
          padding: const EdgeInsets.all(10.0),
          child: SingleChildScrollView(
            child: Center(
              // Center is a layout widget. It takes a single child and positions it
              // in the middle of the parent.
              child: Column(

                mainAxisAlignment: MainAxisAlignment.center,
                children: [


                  InkWell(
                    child: Icon((isPlaying)?Icons.pause_circle_filled:Icons.play_circle_filled,color: Colors.pink,size: 48,),
                    onTap: (){

                      if(isPlaying)
                        {
                          _stop();
                        }else
                          {
                            _speak(text);
                          }
                    },
                  ), Text(
                    text,
                    style: TextStyle(color: Colors.pink,fontSize: 20),
                  ),
                  ]
              ),
            ),
          ),
        ),
         // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }

  initializeTts() {
    _flutterTts = FlutterTts();



    _flutterTts.setStartHandler(() {
      setState(() {
        isPlaying = true;
      });
    });

    _flutterTts.setCompletionHandler(() {
      setState(() {
        isPlaying = false;
      });
    });

    _flutterTts.setErrorHandler((err) {
      setState(() {
        print("error occurred: " + err);
        isPlaying = false;
      });
    });
  }


  Future _speak(String text) async {
    if (text != null && text.isNotEmpty) {
      var result = await _flutterTts.speak(text);
      if (result == 1)
        setState(() {
          isPlaying = true;
        });
    }
  }

  Future _stop() async {
    var result = await _flutterTts.stop();
    if (result == 1)
      setState(() {
        isPlaying = false;
      });
  }

  void setTtsLanguage() async {
    await _flutterTts.setLanguage("en-US");
  }

  @override
  void dispose() {
    super.dispose();
    _flutterTts.stop();
  }
}

 

Now let's run the application and check the result

References

flutter_tts: ^0.8.6

 




Related Questions View All