6/recent/ticker-posts

Text To Speech in Flutter

The provided code demonstrates a Flutter implementation of a Text-to-Speech (TTS) feature. TTS technology allows users to convert written text into spoken words, providing accessibility and convenience. The code includes a user interface where users can input text, adjust parameters such as volume, rate, and pitch, select a language, and convert the entered text into speech. The implementation also provides language selection with corresponding voice options. Overall, this code provides a comprehensive TTS solution that can be integrated into applications to enhance accessibility and user experiences by offering speech output for textual content.

   1. Import the necessary dependencies:

text_to_speech: ^0.2.3

   2. Import this necessary permission to your AndroidManifest.xml

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>

   3. Declare the necessary variables and objects within the state       class:

Color bgColor = const Color(0xff00A67E);
String text = '';
double volume = 1; // Range: 0-1
double rate = 1.0; // Range: 0-2
double pitch = 1.0; // Range: 0-2
String? language;
String? languageCode;
List<String> languages = <String>[];
List<String> languageCodes = <String>[];
String? voice;
TextEditingController textEditingController = TextEditingController();

    4. Implement the speak method, which utilizes the                           TextToSpeech object to speak the given text:

void speak() {
tts.setVolume(volume);
tts.setRate(rate);
if (languageCode != null) {
tts.setLanguage(languageCode!);
}
tts.setPitch(pitch);
tts.speak(text);
}

   5. Override the initState method to initialize the state of the widget:

@override
void initState() {
super.initState();
textEditingController.text = text;
WidgetsBinding.instance.addPostFrameCallback((_) {
initLanguages();
});
}

    6. Implement the initLanguages method to initialize the available languages and voices:

Future<void> initLanguages() async {

// Populate language codes (i.e., en-US)

languageCodes = await tts.getLanguages();

// Populate displayed languages (i.e., English)

final List<String>? displayLanguages = await tts.getDisplayLanguages();
if (displayLanguages == null) {
return;
}

languages.clear();
for (final dynamic lang in displayLanguages) {
languages.add(lang as String);
}

final String? defaultLangCode = await tts.getDefaultLanguage();
if (defaultLangCode != null && languageCodes.contains(defaultLangCode)) {
languageCode = defaultLangCode;
} else {
languageCode = defaultLanguage;
}

language = await tts.getDisplayLanguageByCode(languageCode!);

// Get the voice

voice = await getVoiceByLang(languageCode!);
if (mounted) {
setState(() {});
}
}

    7. Implement the getVoiceByLang method to retrieve the voice for agiven language:

Future<String?> getVoiceByLang(String lang) async {
final List<String>? voices = await tts.getVoiceByLang(languageCode!);
if (voices != null && voices.isNotEmpty) {
return voices.first;
}
return null;
}

  8. Code :

 main.dart

import 'package:flutter/material.dart';
import 'package:flutter_tts/text_to_speech.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: 'Poppins',
primarySwatch: Colors.green,
),
home: const Tts(),
)
;
}
}

 TextToSpeech.dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:text_to_speech/text_to_speech.dart';

class Tts extends StatefulWidget {
const Tts({Key? key}) : super(key: key);

@override
State<Tts> createState() => _TtsState();
}

class _TtsState extends State<Tts> {
final String defaultLanguage = 'en-US';

TextToSpeech tts = TextToSpeech();

Color bgColor = const Color(0xff00A67E);

String text = '';
double volume = 1; // Range: 0-1
double rate = 1.0; // Range: 0-2
double pitch = 1.0; // Range: 0-2

String? language;
String? languageCode;
List<String> languages = <String>[];
List<String> languageCodes = <String>[];
String? voice;

TextEditingController textEditingController = TextEditingController();

bool get supportPause => defaultTargetPlatform != TargetPlatform.android;

bool get supportResume => defaultTargetPlatform != TargetPlatform.android;

void speak() {
tts.setVolume(volume);
tts.setRate(rate);
if (languageCode != null) {
tts.setLanguage(languageCode!);
}
tts.setPitch(pitch);
tts.speak(text);
}

@override
void initState() {
super.initState();
textEditingController.text = text;
WidgetsBinding.instance.addPostFrameCallback((_) {
initLanguages();
});
}

Future<void> initLanguages() async {
/// populate lang code (i.e. en-US)
languageCodes = await tts.getLanguages();

/// populate displayed language (i.e. English)
final List<String>? displayLanguages = await tts.getDisplayLanguages();
if (displayLanguages == null) {
return;
}

languages.clear();
for (final dynamic lang in displayLanguages) {
languages.add(lang as String);
}

final String? defaultLangCode = await tts.getDefaultLanguage();
if (defaultLangCode != null && languageCodes.contains(defaultLangCode)) {
languageCode = defaultLangCode;
} else {
languageCode = defaultLanguage;
}
language = await tts.getDisplayLanguageByCode(languageCode!);

/// get voice
voice = await getVoiceByLang(languageCode!);

if (mounted) {
setState(() {});
}
}

Future<String?> getVoiceByLang(String lang) async {
final List<String>? voices = await tts.getVoiceByLang(languageCode!);
if (voices != null && voices.isNotEmpty) {
return voices.first;
}
return null;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Text-to-Speech'),
backgroundColor: bgColor,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: Column(
children: <Widget>[
TextField(
controller: textEditingController,
maxLines: 5,
cursorColor: bgColor,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide: BorderSide(),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: bgColor),
),
),
onChanged: (String newText) {
setState(() {
text = newText;
});
},
),

Row(
children: <Widget>[
const Text('Volume'),
Expanded(
child: Slider(
value: volume,
min: 0,
max: 1,
activeColor: bgColor,
inactiveColor: bgColor.withOpacity(0.3),
label: volume.round().toString(),
onChanged: (double value) {
initLanguages();
setState(() {
volume = value;
});
},
),
),
Text('(${volume.toStringAsFixed(2)})'),
],
),
Row(
children: <Widget>[
const Text('Rate'),
Expanded(
child: Slider(
value: rate,
min: 0,
max: 2,
activeColor: bgColor,
inactiveColor: bgColor.withOpacity(0.3),
label: rate.round().toString(),
onChanged: (double value) {
setState(() {
rate = value;
});
},
),
),
Text('(${rate.toStringAsFixed(2)})'),
],
),
Row(
children: <Widget>[
const Text('Pitch'),
Expanded(
child: Slider(
value: pitch,
min: 0,
max: 2,
activeColor: bgColor,
inactiveColor: bgColor.withOpacity(0.3),
label: pitch.round().toString(),
onChanged: (double value) {
setState(() {
pitch = value;
});
},
),
),
Text('(${pitch.toStringAsFixed(2)})'),
],
),
Row(
children: <Widget>[
const Text('Language'),
const SizedBox(
width: 20,
),
DropdownButton<String>(
value: language,
icon: Icon(Icons.arrow_downward,color: bgColor,),
iconSize: 24,
elevation: 16,
style: TextStyle(color:bgColor),
underline: Container(
height: 2,
color: bgColor,
),
onChanged: (String? newValue) async {
languageCode =
await tts.getLanguageCodeByName(newValue!);
voice = await getVoiceByLang(languageCode!);
setState(() {
language = newValue;
});
},
items: languages
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
],
),
const SizedBox(
height: 20,
),
Row(
children: <Widget>[
const Text('Voice'),
const SizedBox(
width: 20,
),
Text(voice ?? '-'),
],
),
const SizedBox(
height: 20,
),
Row(
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.only(right: 10),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(bgColor),
),
child: const Text('Stop'),
onPressed: () {
tts.stop();
},
),
),
),
if (supportPause)
Expanded(
child: Container(
padding: const EdgeInsets.only(right: 10),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(bgColor),
),
child: const Text('Pause'),
onPressed: () {
tts.pause();
},
),
),
),
if (supportResume)
Expanded(
child: Container(
padding: const EdgeInsets.only(right: 10),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(bgColor),
),
child: const Text('Resume'),
onPressed: () {
tts.resume();
},
),
),
),
Expanded(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(bgColor),
),
child: const Text('Speak'),
onPressed: () {
speak();
},
))
],
)
],
),
),
),
),
),
);
}
}

This code defines a Flutter widget that provides a user interface for text input, volume/rate/pitch adjustment, language selection, and TTS actions such as speak, stop, pause, and resume. The implementation relies on the TextToSpeech class from the text_to_speech package for the TTS functionality.

Please note that the code assumes the existence of the text_to_speech package and its dependencies. Make sure to import and install the required packages before running this code.

follow my Instagram account :

https://www.instagram.com/nature.pulse_/

   Output :




Post a Comment

0 Comments