flutter_tts

repository·master·Indexed 20 days ago

https://github.com/dlutton/flutter_tts

A Flutter plugin for Text-to-Speech (TTS) functionality supporting Android, iOS, Web, Windows, and macOS. It provides control over speech rate, pitch, volume, language selection, and voice configuration. Features include speech synthesis to files on iOS and Android, and integration with the browser's SpeechSynthesis API for Web platforms.

Tokens
1.9K
Snippets
7
Records
9
Agent score
71%

What's inside flutter_tts

  1. Configure iOS for flutter_tts

    master

    When using flutter_tts on iOS, you can manage the audio session to control how your app's speech interacts with other audio (like background music).

    Use setIosAudioCategory to set the category, options, and mode. For example, to allow background music and in-app audio to play simultaneously, use IosTextToSpeechAudioCategory.ambient with IosTextToSpeechAudioCategoryOptions.mixWithOthers.

    await flutterTts.setIosAudioCategory(
      IosTextToSpeechAudioCategory.ambient,
      [
        IosTextToSpeechAudioCategoryOptions.allowBluetooth,
        IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
        IosTextToSpeechAudioCategoryOptions.mixWithOthers
      ],
      IosTextToSpeechAudioMode.voicePrompt
    );
  2. Configure Android for flutter_tts

    master

    To use flutter_tts on Android, you must perform the following configuration steps:

    1. Set Minimum SDK Version: In android/app/build.gradle, set minSdkVersion to 21 or higher.
    2. Update Kotlin Gradle Plugin:
      • If your project uses an older Flutter version, update ext.kotlin_version to 1.9.10 in android/build.gradle.
      • Otherwise, update the org.jetbrains.kotlin.android plugin version to 1.9.10 in android/settings.gradle.
    3. Declare TTS Service Intent: For apps targeting Android 11+, add the TTS_SERVICE intent to your AndroidManifest.xml within a <queries> block to allow the app to interact with the TTS engine.
    // android/app/build.gradle
    minSdkVersion 21
    // android/build.gradle
    ext.kotlin_version = '1.9.10'
    <!-- AndroidManifest.xml -->
    <queries>
      <intent>
        <action android:name="android.intent.action.TTS_SERVICE" />
      </intent>
    </queries>
  3. Customize the iOS launch screen assets

    master

    To change the image displayed during the app's launch on iOS, you can either replace the image files directly in the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode for a more visual approach.

    Using Xcode:

    1. Open the iOS workspace in Xcode by running open ios/Runner.xcworkspace from your terminal.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog.
    open ios/Runner.xcworkspace
  4. Web-specific speech progress tracking

    master

    On the Web, the plugin listens to the onBoundary event of the SpeechSynthesisUtterance. It calculates word boundaries by looking for whitespace or punctuation in the text following the charIndex provided by the browser.

    When a word boundary is detected, it invokes the speak.onProgress method via the platform channel with the following payload:

    KeyTypeDescription
    textStringThe full text being spoken
    startintThe starting character index of the word
    endintThe ending character index of the word
    wordStringThe specific word being spoken
  5. Web platform implementation details for FlutterTtsPlugin

    master

    The flutter_tts plugin on the Web uses the browser's SpeechSynthesis API via SpeechSynthesisUtterance.

    Key Behaviors:

    • Initialization: The plugin attempts to initialize SpeechSynthesisUtterance. If it fails, the supported flag is set to false, and subsequent method calls will not execute.
    • State Management: The plugin tracks the speech state using TtsState (playing, stopped, paused, continued).
    • Non-Local Service Workaround: For voices that are not local services (often remote cloud voices in browsers), the plugin implements a periodic timer that calls synth.pause() and synth.resume() every 14 seconds to prevent the browser from idling or timing out the speech session.
  6. Synthesize speech to a file

    master

    On iOS (13+) and Android, you can save the spoken text to a file. Note that file extensions may vary by platform (e.g., .wav for Android, .caf for iOS).

    // iOS, macOS, and Android only
    await flutterTts.synthesizeToFile(
      "Hello World", 
      Platform.isAndroid ? "tts.wav" : "tts.caf", 
      false
    );
  7. Listen to speech lifecycle events

    master

    You can register handlers to respond to different stages of the text-to-speech lifecycle, such as when speech starts, completes, pauses, or encounters an error.

    flutterTts.setStartHandler(() {
      // Triggered when speech starts
    });
    
    flutterTts.setCompletionHandler(() {
      // Triggered when speech finishes
    });
    
    flutterTts.setProgressHandler((String text, int startOffset, int endOffset, String word) {
      // Triggered during speech to provide progress and current word
    });
    
    flutterTts.setErrorHandler((msg) {
      // Triggered on error
    });
    
    flutterTts.setPauseHandler((msg) {
      // Triggered when speech is paused (Android, iOS, Web)
    });
    
    flutterTts.setContinueHandler((msg) {
      // Triggered when speech resumes (Android, iOS, Web)
    });
  8. Use the core FlutterTts API

    master

    The FlutterTts class provides methods to control speech playback, manage languages, and configure voice parameters.

    Common Methods:

    • speak(String text): Starts speaking the provided text.
    • stop(): Stops current speech.
    • pause(): Pauses speech (Supported on iOS, Android, and Web. On Android, this uses a workaround via onRangeStart()).
    • getLanguages: Returns a list of available language codes.
    • setLanguage(String languageCode): Sets the speech language (e.g., en-US).
    • setSpeechRate(double rate): Sets the speed of speech.
    • setVolume(double volume): Sets the volume level.
    • setPitch(double pitch): Sets the pitch of the voice.
    • getVoices: Returns a list of available voices as Maps containing keys like name and locale (and platform-specific keys like identifier or quality).
    • setVoice(Map voice): Sets the active voice using a map (e.g., {"name": "Karen", "locale": "en-AU"}).
    FlutterTts flutterTts = FlutterTts();
    
    await flutterTts.speak("Hello World");
    await flutterTts.setLanguage("en-US");
    await flutterTts.setSpeechRate(1.0);
    await flutterTts.setVolume(1.0);
    await flutterTts.setPitch(1.0);