In this tutorial, I'm going to show you how to add a text to speech feature to your app. We are not going to use any API and this will be pretty simple using the flutter_text_to_speech package.
Before moving on, let's see an illustration of what we will be able to achieve with this tutorial.
STEPS TO REPRODUCE:
- Add the package dependency to your pubspec.yaml file
dependencies:
flutter:
sdk: flutter
flutter_text_to_speech: ^3.0.7
- For this particular package to work, you will have to change your minSdkVersion value to 21. Navigate to the following file and use the below code to make the necessary change - /android/app/build.gradle
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.texttospeech"
minSdkVersion 21 //make this to 21
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
- Finally, use the following code in your main.dart file to get a working example as shown in the video.
import 'package:flutter/material.dart'; import 'package:flutter_text_to_speech/flutter_text_to_speech.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Text To Speech', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Text To Speech'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { VoiceController _voiceController; String text = 'This is an example tutorial of using text to speech in a flutter application! The example is provided on fluttercentral website.'; @override void initState() { _voiceController = FlutterTextToSpeech.instance.voiceController(); super.initState(); } @override void dispose() { super.dispose(); _voiceController.stop(); } _playVoice() { _voiceController.init().then((_) { _voiceController.speak( text, VoiceControllerOptions(), ); }); } _stopVoice() { _voiceController.stop(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( text, textAlign: TextAlign.center, ), SizedBox( height: 10, ), RaisedButton( onPressed: _playVoice, color: Colors.blue, child: Text('Play Voice'), ), RaisedButton( onPressed: _stopVoice, color: Colors.blue, child: Text('Stop Voice'), ), ], ), ), ); } }
I hope you liked this tutorial.
If you have any doubts, drop them in comments :)