flutter_tts 0.9.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 98

Text To Speech #

pub package

A flutter text to speech plugin (Swift,Java)

Features #

  • [x] Android, iOS, & Web
    • [x] speak
    • [x] stop
    • [x] get languages
    • [x] set language
    • [x] set speech rate
    • [x] set speech volume
    • [x] set speech pitch
    • [x] is language available
  • [x] Android, iOS
    • [x] get voices
    • [x] set voice
  • [x] Android
    • [x] set Silence
    • [x] synthesize to file

Usage #

Web #

Website from the example directory.

Android #

Change the minimum Android sdk version to 21 (or higher) in your android/app/build.gradle file.

minSdkVersion 21

iOS #

There's a known issue with integrating plugins that use Swift into a Flutter project created with the Objective-C template. Flutter#16049

Example

To use this plugin :

  dependencies:
    flutter:
      sdk: flutter
    flutter_tts:
  • instantiate FlutterTts
FlutterTts flutterTts = FlutterTts();

speak, stop, getLanguages, setLanguage, setSpeechRate, setVolume, setPitch, isLanguageAvailable #

Future _speak() async{
    var result = await flutterTts.speak("Hello World");
    if (result == 1) setState(() => ttsState = TtsState.playing);
}

Future _stop() async{
    var result = await flutterTts.stop();
    if (result == 1) setState(() => ttsState = TtsState.stopped);
}

Future _synthesizeToFile() async{
    var result = await flutterTts.synthesizeToFile("Hello World", "tts.wav");
}

List<dynamic> languages = await flutterTts.getLanguages;

await flutterTts.setLanguage("en-US");

await flutterTts.setSpeechRate(1.0);

await flutterTts.setVolume(1.0);

await flutterTts.setPitch(1.0);

await flutterTts.isLanguageAvailable("en-US");

Listening for platform calls #

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

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

flutterTts.setErrorHandler((msg) {
  setState(() {
    ttsState = TtsState.stopped;
  });
});

Getting Started #

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation.

ChangeLog #

0.9.1 #

  • Android: Fixing method call error

0.9.0 #

  • Android: Adding synthesize to file

0.8.7 #

  • Android: Fix sporadic ANR on initialization

0.8.6 #

  • iOS: Reducing volume of other sessions while TTS is playing

0.8.5 #

  • Android: Fix Android async platform initialization
  • Android: Removing initHandler

0.8.2 #

  • Web: Adding isLanguageAvailable method
  • All: Fixing isLanguageAvailable platform channel and making it case insensitive

0.8.0 #

  • Web: Adding Web Support

0.7.0 #

  • iOS: Adding Swift version 4.2 to podspec and correct audio playback category

0.6.0 #

  • Android: AndroidX support

0.5.2 #

  • Android: Bug Fix on isLanguageAvailable

0.5.1 #

  • Applying flutter format to fix health suggestion

0.5.0 #

  • Android: Adding silence before speak
  • Android: Removing deprecated API

0.2.6 #

  • IOS: Add voice selection implementation

0.2.5 #

  • Android: Ensure invokeMethod runs on main thread

0.2.4 #

  • Android: setting minSDK back to 21 and adding instructions to readme
  • Android: Adding fallback for getLanguages and defaultLanguage

0.2.3 #

  • IOS: Audio continues with the Ring/Silent switch set to silent

0.2.2 #

  • Android: Fixing Locale bug

0.2.1 #

  • IOS: Fixing getLanguages bug

0.2.0 #

  • Android: Adding exception catch for samsung devices
  • Android: Using default com.google.android.tts engine
  • Android: Get and Set Voice
  • Android: InitHandler
  • Cleaning up the example

0.1.2 #

  • Support for Android background execution
  • Updating Android build gradle version to 3.2.1

0.1.1 #

  • Fixing TTS bound error in the example
  • Fixing default voice language not found error on Android

0.1.0 #

  • Updating version for improved maintenance score
  • Updating package description for improved maintenance score

0.0.8 #

  • Adding analysis_options.yaml for improved health score
  • Fixing info/errors from flutter analyze

0.0.7 #

  • Updating SDK version in pubspec.yaml
  • Adding package link to README
  • Fixing language string warning received from xcode

0.0.6 #

  • Android: Upgrading Gradle 4.1 to 4.4
  • Android: Setting minSdk version to 21
  • Android: Adding try/catch to getAvailableLanguages & getDefaultVoice methods (Issues with API 21 & 22)

0.0.5 #

  • Adding IOS/Android isLanguageAvailable
  • Rename setRate to setSpeechRate

0.0.4 #

  • Simplify podspec for Cocoapods 1.5.0

0.0.3 #

  • Adding IOS/Android speech pitch and volume

0.0.2 #

  • Flutter formatting and fixing pubspec sdk versioning

0.0.1 #

  • first POC :
    • methods : speak, stop, setRate, setLangauge, getLanguages
    • a globalHandler for completion

example/lib/main.dart

import 'dart:async';

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

enum TtsState { playing, stopped }

class _MyAppState extends State<MyApp> {
  FlutterTts flutterTts;
  dynamic languages;
  String language;
  double volume = 0.5;
  double pitch = 1.0;
  double rate = 0.5;

  String _newVoiceText;

  TtsState ttsState = TtsState.stopped;

  get isPlaying => ttsState == TtsState.playing;

  get isStopped => ttsState == TtsState.stopped;

  @override
  initState() {
    super.initState();
    initTts();
  }

  initTts() {
    flutterTts = FlutterTts();

    _getLanguages();

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

    flutterTts.setCompletionHandler(() {
      setState(() {
        print("Complete");
        ttsState = TtsState.stopped;
      });
    });

    flutterTts.setErrorHandler((msg) {
      setState(() {
        print("error: $msg");
        ttsState = TtsState.stopped;
      });
    });
  }

  Future _getLanguages() async {
    languages = await flutterTts.getLanguages;
    if (languages != null) setState(() => languages);
  }

  Future _speak() async {
    await flutterTts.setVolume(volume);
    await flutterTts.setSpeechRate(rate);
    await flutterTts.setPitch(pitch);

    if (_newVoiceText != null) {
      if (_newVoiceText.isNotEmpty) {
        var result = await flutterTts.speak(_newVoiceText);
        if (result == 1) setState(() => ttsState = TtsState.playing);
      }
    }
  }

  Future _stop() async {
    var result = await flutterTts.stop();
    if (result == 1) setState(() => ttsState = TtsState.stopped);
  }

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

  List<DropdownMenuItem<String>> getLanguageDropDownMenuItems() {
    var items = List<DropdownMenuItem<String>>();
    for (String type in languages) {
      items.add(DropdownMenuItem(value: type, child: Text(type)));
    }
    return items;
  }

  void changedLanguageDropDownItem(String selectedType) {
    setState(() {
      language = selectedType;
      flutterTts.setLanguage(language);
    });
  }

  void _onChange(String text) {
    setState(() {
      _newVoiceText = text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Flutter TTS'),
            ),
            body: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(children: [
                  _inputSection(),
                  _btnSection(),
                  languages != null ? _languageDropDownSection() : Text(""),
                  _buildSliders()
                ]))));
  }

  Widget _inputSection() => Container(
      alignment: Alignment.topCenter,
      padding: EdgeInsets.only(top: 25.0, left: 25.0, right: 25.0),
      child: TextField(
        onChanged: (String value) {
          _onChange(value);
        },
      ));

  Widget _btnSection() => Container(
      padding: EdgeInsets.only(top: 50.0),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
        _buildButtonColumn(
            Colors.green, Colors.greenAccent, Icons.play_arrow, 'PLAY', _speak),
        _buildButtonColumn(
            Colors.red, Colors.redAccent, Icons.stop, 'STOP', _stop)
      ]));

  Widget _languageDropDownSection() => Container(
      padding: EdgeInsets.only(top: 50.0),
      child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        DropdownButton(
          value: language,
          items: getLanguageDropDownMenuItems(),
          onChanged: changedLanguageDropDownItem,
        )
      ]));

  Column _buildButtonColumn(Color color, Color splashColor, IconData icon,
      String label, Function func) {
    return Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
              icon: Icon(icon),
              color: color,
              splashColor: splashColor,
              onPressed: () => func()),
          Container(
              margin: const EdgeInsets.only(top: 8.0),
              child: Text(label,
                  style: TextStyle(
                      fontSize: 12.0,
                      fontWeight: FontWeight.w400,
                      color: color)))
        ]);
  }

  Widget _buildSliders() {
    return Column(
      children: [_volume(), _pitch(), _rate()],
    );
  }

  Widget _volume() {
    return Slider(
        value: volume,
        onChanged: (newVolume) {
          setState(() => volume = newVolume);
        },
        min: 0.0,
        max: 1.0,
        divisions: 10,
        label: "Volume: $volume");
  }

  Widget _pitch() {
    return Slider(
      value: pitch,
      onChanged: (newPitch) {
        setState(() => pitch = newPitch);
      },
      min: 0.5,
      max: 2.0,
      divisions: 15,
      label: "Pitch: $pitch",
      activeColor: Colors.red,
    );
  }

  Widget _rate() {
    return Slider(
      value: rate,
      onChanged: (newRate) {
        setState(() => rate = newRate);
      },
      min: 0.0,
      max: 1.0,
      divisions: 10,
      label: "Rate: $rate",
      activeColor: Colors.green,
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_tts: ^0.9.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_tts/flutter_tts.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
95
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
98
Learn more about scoring.

We analyzed this package on Apr 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
flutter_web_plugins 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8