Text to Speech 1.0.0 · manual

Text to Speech manual

Version 1.0.0. For a short overview see the README. Release history is in the changelog.

Overview

Text to Speech puts one small C# API over the speech engines the operating system already has. You ask for a text to be spoken, or rendered to an AudioClip, and you get events with the word being heard.

  • Windows (64-bit player and Editor): Windows.Media.SpeechSynthesis, through a small native DLL shipped with its C++ source.
  • Android: the device's android.speech.tts.TextToSpeech engine, through Java source that Unity compiles with Gradle.
  • Other platforms: not supported. The package compiles there and requests fail with SpeechErrorCode.NotSupported.

You do not set up a cloud account, a key, a voice file or a permission. The package contains no voice and no audio, and it does not download any. Everything runs on the device.

Requirements

  • Unity 6000.0.84f1 or newer. Tested with 6000.0.84f1 and 6000.3.12f1 only; see Tested on.
  • Windows: 64-bit (x64) Windows 10 or Windows 11, player or Editor. Rate, pitch and volume need Windows 10 version 1709 or newer. Voices come from Settings > Time & language > Speech. Tested on Windows 11 only.
  • Android: a text-to-speech engine on the device (Google Speech Services on most devices). The library is built for minSdk 23 (Unity 6000.0 can target API 23; Unity 6000.3 raises its own minimum to 25). It was run on API 26 and API 36 emulators only; API 23 to 25 were not run. Word events need API 26 and an engine that reports them.
  • The Unity UI package (com.unity.ugui, in every new project) is needed only for SubtitleHighlighter and the Demo sample. Without it those scripts are not compiled; the rest of the package does not change. TextMeshPro, which comes with uGUI 2.0, is optional for the highlighter and needs the TMP Essential Resources.
  • The package depends only on the built-in modules Android JNI and Audio. It adds no permission to your Android manifest.

Installation

From the Asset Store

  1. Open the Package Manager: Window > Package Manager in Unity 6.0, Window > Package Management > Package Manager in Unity 6.3.
  2. Select My Assets and find Text to Speech.
  3. Click Install.

On Windows, close the Unity Editor before you update the package. The Editor keeps LuanrobsSpeech.dll loaded once the package has used it, so an update cannot replace it, and an Editor that stays open continues with the old binary until it restarts.

Demo scenes

In the Package Manager, select Text to Speech, open the Samples tab and import Demo. Unity copies the sample into your project under Assets/Samples.

Scene What it shows
00 Menu Launcher with one button per scene. On a platform the package does not support, it says so in one line.
01 Voice Playground A voice drop-down with an offline-only toggle, sliders for rate, pitch and volume, a text field, and Speak, Synthesize & Play and Stop buttons. A line counts the word events. On Android, an Install voice data button.
02 Narrated Menu Five buttons. Every time the selected button changes, its label is spoken with Interrupt. A toggle turns the narration off.
03 Talking Character A figure made of primitives with a 3D AudioSource and a SpeechSource in AudioSource mode. The mouth follows the output level and the camera moves, so the sound pans.
04 Subtitles A paragraph with a SubtitleHighlighter. Speak uses the engine's word events in real time; Play as clip uses the timings that come with the clip.

Things to know:

  • The sample needs uGUI. In a project without it Unity skips the sample's scripts instead of failing to compile.
  • Add all five scenes to the Scene List in File > Build Profiles, with 00 Menu first. This is needed in the Editor as well as in a build, because the scenes load each other by name. A missing scene is reported on screen.
  • The scenes work with the Input Manager, the Input System or both. They create their own EventSystem.
  • 00 Menu has a small luanrobs.com/text-to-speech line in its footer that opens the product page only when it is clicked.
  • The sample uses Unity's built-in font and shapes generated by its scene builder. It contains no voice and no audio file.

Quick start

Speak a sentence

using Luanrobs.Speech;
using UnityEngine;

public class SayHello : MonoBehaviour
{
    private void Start()
    {
        // The engine starts on the first call; the request waits until it is ready.
        TextToSpeech.Speak("Hello from the voices on this device.");
    }
}

Speak returns a SpeechUtterance. You can ignore it, subscribe to its events, or wait for it in a coroutine with yield return utterance;.

Synthesize to an AudioClip

using System.Collections;
using Luanrobs.Speech;
using UnityEngine;

public class SayWithClip : MonoBehaviour
{
    [SerializeField] private AudioSource audioSource;

    private AudioClip ownedClip;

    private IEnumerator Start()
    {
        SpeechUtterance utterance = TextToSpeech.Synthesize("This sentence plays on an AudioSource.");
        yield return utterance;

        if (utterance.Status != SpeechStatus.Completed)
        {
            Debug.LogWarning(utterance.Error != null ? utterance.Error.ToString() : utterance.Status.ToString());
            yield break;
        }

        ownedClip = utterance.Clip; // a clip from Synthesize belongs to you
        audioSource.clip = ownedClip;
        audioSource.Play();
    }

    private void OnDestroy()
    {
        if (ownedClip != null)
            Destroy(ownedClip);
    }
}

Because the output is an ordinary AudioClip, it follows your AudioSource: 3D position, mixer groups, effects, AudioListener volume and pause.

SpeechSource component

  1. Select a GameObject, then Add Component > luanrobs > Speech Source, or choose GameObject > Audio > Speech Source (luanrobs).
  2. Type a text (or assign a Text Asset), pick a voice, set rate, pitch and volume.
  3. Choose the output: Speak (the platform plays it) or Audio Source (a synthesized clip plays on an AudioSource).
  4. Call Play() from a Button's On Click (), from code, or tick Play On Enable.

SubtitleHighlighter

  1. On a uGUI Text that shows your subtitle, Add Component > luanrobs > Subtitle Highlighter.
  2. Drag a SpeechSource into Source and press Play. The word being heard is coloured.

With no source assigned, the highlighter follows every TextToSpeech.Speak request instead.

Voices and languages

Voices are read from the engine once per initialization. Wait for TextToSpeech.Initialized (or check TextToSpeech.IsReady) before you read them.

using Luanrobs.Speech;
using UnityEngine;

public class ListVoices : MonoBehaviour
{
    private void Start()
    {
        if (TextToSpeech.IsReady)
            Print();
        else
            TextToSpeech.Initialized += Print;

        TextToSpeech.Initialize();
    }

    private void OnDestroy()
    {
        TextToSpeech.Initialized -= Print;
    }

    private void Print()
    {
        foreach (SpeechVoice voice in TextToSpeech.GetVoices("en"))
            Debug.Log(voice.Name + " | " + voice.Language + " | " + voice.Gender + " | id " + voice.Id);

        TextToSpeech.Speak("Hello.", new SpeechOptions { language = "en-US" });
    }
}

A SpeechVoice has:

Member Meaning
Id Platform identifier, stable on the same device. Windows: the voice token path. Android: the voice name (for example en-us-x-sfg-local). Pass it in SpeechOptions.voiceId.
Name A name to show a person.
Language BCP-47 tag with a hyphen, such as en-US or pt-BR; empty when unknown.
Gender Female or Male on Windows; always Unknown on Android.
RequiresNetwork, IsInstalled, IsOffline Android flags. On Windows every voice is installed and needs no network. IsOffline is !RequiresNetwork && IsInstalled.
Quality Android voice quality rating (100 to 500); 0 on Windows.
IsDefault The engine's default voice (at most one).

TextToSpeech.GetVoices(language, offlineOnly) filters the list: a bare language such as en matches every voice of that language; a regional tag such as en-US matches only that tag. offlineOnly is true by default.

How a voice is chosen

For each request, in this order, among the voices the options allow (offline ones when offlineOnly is true, which is the default):

  1. voiceId is set and a voice has that id: that voice.
  2. language is set: the voices whose tag equals it; if none and the request has a region, the voices of the same language (those with the same region or script subtag first). A bare language matches every voice of that language. Among the candidates, the engine's default voice wins, then the highest Quality, then the engine's order.
  3. voiceId was set but not found, and no language is set: the request fails with VoiceNotFound.
  4. Neither is set: the engine's default voice, else the first voice with the highest Quality.

When nothing matches the language the request fails with LanguageNotAvailable, or with VoiceNotInstalled when the engine lists a matching voice that is not installed or needs the network and offlineOnly is on. TextToSpeech.ResolveVoice(options) returns the voice a request would use, or null when the engine is not ready.

Voices installed while the app runs

The voice list is read once per initialization. After the user installs a voice, call TextToSpeech.Shutdown() and then TextToSpeech.Initialize(); the new voices appear when Initialized is raised. Queued and running requests are stopped by Shutdown.

Options

SpeechOptions is a serializable class with public fields. Every request copies the options it is given, so changing an instance later does not affect requests already made. null options mean defaults.

Field Type Default Description
voiceId string empty SpeechVoice.Id of the voice to use.
language string empty BCP-47 tag (en-US) or bare language (en), used when voiceId is empty or not found.
rate float 1 Speaking rate multiplier, 0.5 to 3.
pitch float 1 Pitch multiplier, 0.5 to 2.
volume float 1 Volume of the speech, 0 to 1.
queueMode SpeechQueueMode Enqueue Enqueue or Interrupt. Used by Speak only.
ssml bool false The text is SSML and is passed to the engine unchanged. Windows only.
offlineOnly bool true Use only installed voices that work without the network.

Notes:

  • A value outside its range makes the request throw ArgumentOutOfRangeException (see Error handling); nothing is clamped silently.
  • Rate and pitch are multipliers whose audible effect differs per engine.
  • Volume of Speak goes to the engine, whose curve is its own: on the Windows voice that was measured, 0.5 gave about a quarter of the signal level, not a half. Volume of Synthesize is applied by the package to the samples, linearly, and is the same on both platforms.
  • With ssml on, the text must be SSML for the engine, and word boundary indexes point into the SSML string, not into the plain text a person reads.

Speaking: queue, interrupt, stop, cancel

TextToSpeech.Speak(text, options) queues a request and returns its SpeechUtterance at once.

  • Queue. Speak requests run one after another in the order they were made (SpeechQueueMode.Enqueue). Speak and Synthesize requests have separate queues. Requests made before the engine is ready wait for it.
  • Interrupt. With queueMode = SpeechQueueMode.Interrupt, the Speak request that is playing and every queued Speak request are stopped (each raises Finished with Status = Stopped) and the new one starts. This is how a narrated menu avoids a backlog when the user moves quickly. Synthesize ignores queueMode.
  • Stop. TextToSpeech.Stop() stops the playing Speak request and drops the queued ones. TextToSpeech.StopAll() does that and also cancels Synthesize requests.
  • Cancel. SpeechUtterance.Cancel() ends one request, queued or running. It does nothing when the request is done.
  • Pause. Speech cannot be paused and resumed. By default Stop() is called when the application is paused (on Android, when it goes to the background); set TextToSpeech.StopOnPause = false to keep speaking. Synthesize requests are not affected. A clip you play on an AudioSource can be paused with the AudioSource.
  • State. IsSpeaking is true while a Speak request is running. IsBusy is true while any request is queued or running.

A text must not be null, empty or only white space (ArgumentNullException, ArgumentException) and must not be longer than TextToSpeech.MaxTextLength (3999 UTF-16 units; ArgumentException). The whole text is rendered before it starts playing, on Windows too, so a long text starts late: split it by sentence for narration.

Synthesizing an AudioClip

TextToSpeech.Synthesize(text, options) renders the text and gives you the result in SpeechUtterance.Clip when Finished is raised with Status = Completed. Duration is the clip length and WordBoundaries holds the word timings.

  • The clip is mono or stereo PCM as the engine delivers it (on Windows the measured clip was mono, 16 kHz, 16 bit). Unity resamples it when it plays.
  • The clip belongs to you: destroy it when you are done. The clip of an utterance returned by a SpeechClipCache belongs to the cache.
  • Nothing is streamed: the clip appears when the whole text is rendered.
  • SpeechOptions.volume is applied to the samples by the package, linearly.
  • Failures arrive as Status = Failed with Error set; InvalidAudio means the engine produced audio the package cannot read, and OutputError that Unity could not create the clip.

Events

There are two sets with the same meaning: static events on TextToSpeech (every request) and events on each SpeechUtterance (that request only). For each notification the utterance's own event is raised first, then the static one.

Event Arguments Raised when
Initialized none The engine is connected and the voice list is available.
InitializationFailed SpeechError The engine could not be started within the timeout, or at all.
Started SpeechUtterance Speech is heard (Speak), or the clip is ready and about to be reported (Synthesize).
WordBoundary SpeechUtterance, SpeechWordBoundary A word starts (Speak, in real time), after Started.
Error SpeechUtterance, SpeechError A request failed. Raised right before Finished. Static event only; read utterance.Error on the utterance.
Finished SpeechUtterance The request is over, whatever the outcome: Completed, Stopped or Failed.

Rules:

  • All events are raised on the main thread, from the package's Update, after the state they announce is in place. A handler may call any member of the API, including Speak, Stop and Shutdown.
  • Per request: Started zero or one time, then WordBoundary zero or more times, then exactly one Finished.
  • Requests stopped by Stop, StopAll, Cancel, an interrupt or Shutdown raise Finished inside the call that stopped them. Completed and Failed outcomes are raised from the next frame, never inside the call that made the request.
  • A subscriber that throws is logged with Debug.LogException and the others still run.
  • Finished events of requests stopped when the application quits are raised during quit: handlers must tolerate that.
  • Static event subscribers are dropped when Play mode starts (see Domain Reload), so subscribe in Start or OnEnable and unsubscribe in OnDisable.

Word events and timings

Where Timings
Speak on Windows From the engine, in real time.
Speak on Android From the engine's onRangeStart callback, on API 26 and newer, when the engine reports it. Below API 26, or with an engine that does not report ranges, no WordBoundary event is raised.
Synthesize on Windows From the engine's word cues.
Synthesize on Android From onRangeStart when it is delivered; otherwise estimated.
Synthesize, engine reported none Estimated by the package, marked SpeechWordBoundary.IsEstimated.

A SpeechWordBoundary has Start and Length (UTF-16 indexes into the string you passed; a character outside the Basic Multilingual Plane counts 2), End, Time (seconds from the start of the audio, NaN when unknown), HasTime and IsEstimated.

Estimated timings are a fallback. The package finds the words in the text (a word starts at a letter or a digit and runs over letters, digits and combining marks, with an apostrophe kept inside a word; a lone combining mark, or the emoji variation selector in "❤️", is not a word), measures where the speech sits in the clip (leading and trailing silence is left out), and spreads the words across that span in proportion to word length plus one. Expect them to drift by a fraction of a second on texts with long pauses or numbers. Text written without spaces (Chinese, Japanese, Thai) is one word per run of letters, so a whole sentence can get a single estimated boundary. Estimates are not made for SSML, whose indexes point into markup.

SpeechUtterance.WordIndexAt(seconds) returns the index in WordBoundaries of the word heard at that time, or -1 before the first word.

To follow a clip played on an AudioSource, compare audioSource.time with the boundaries. SpeechSource does this for you.

The clip cache

SpeechClipCache renders a text once and returns the stored clip afterwards, so repeated lines (a button label, a recurring phrase) cost nothing after the first time.

using Luanrobs.Speech;
using UnityEngine;

public class CachedLines : MonoBehaviour
{
    [SerializeField] private AudioSource audioSource;

    private SpeechClipCache cache;

    private void Awake()
    {
        cache = new SpeechClipCache(8);
    }

    public void Say(string line)
    {
        SpeechUtterance utterance = cache.GetOrSynthesize(line);
        utterance.Finished += OnReady;
    }

    private void OnReady(SpeechUtterance utterance)
    {
        if (utterance.Status != SpeechStatus.Completed)
            return;

        audioSource.clip = utterance.Clip; // owned by the cache: do not destroy it
        audioSource.Play();
    }

    private void OnDestroy()
    {
        cache.Dispose(); // destroys every stored clip
    }
}
  • The key is the engine, the text and the options (voiceId, language, rate, pitch, volume, ssml, offlineOnly); queueMode does not count.
  • GetOrSynthesize returns an utterance: FromCache is true on a hit, whose Finished is raised on the next frame (the static events are not raised for a hit). A request in flight with the same key returns the same utterance, so a Cancel() from one caller cancels it for every caller of that key.
  • TryGet(text, options, out clip, out wordBoundaries) looks up without rendering.
  • The default Capacity is 32 clips. Beyond it, the least recently used clip is destroyed. Clear() and Dispose() destroy every stored clip. Destroy the cache when you leave the scene that uses it.
  • Clear() leaves requests in flight running; they are stored when they complete. Dispose() detaches them instead: they are not cancelled, and when one completes its clip is destroyed at once (the cache owned it), before your own Finished handlers run. After Dispose(), GetOrSynthesize throws ObjectDisposedException and TryGet finds nothing.
  • A failed or stopped request stores nothing.
  • Clips are in memory: a few seconds of speech is a few hundred kilobytes (about 32 KB per second for the 16 kHz mono 16 bit clip measured on Windows).

SpeechSource component

Add Component > luanrobs > Speech Source. One per GameObject.

Field Description
Text, Text Asset The text to speak. When a Text Asset is assigned it is used instead of Text.
Options The SpeechOptions of the component (voice, language, rate, pitch, volume, queue mode, SSML, offline only).
Output Speak: the platform plays the text. Audio Source: a synthesized clip plays on an AudioSource.
Audio Source Used in Audio Source mode. If empty, the component uses one on the same GameObject, and adds one (with Play On Awake off) if there is none.
Cache Clips In Audio Source mode, keep rendered clips in the component's own cache (16 clips).
Play On Enable Calls Play() when the component is enabled in Play mode.
On Started, On Word, On Finished, On Error UnityEvents. On Word passes the start index and length of the word; On Error passes the message.

Members: Play(), Play(string text), Stop(), IsPlaying, Current (the SpeechUtterance), EffectiveText, the properties of the fields above, and the C# events Started, WordReached and Finished.

Behaviour:

  • Play() stops the component's previous playback first. An empty text does nothing.
  • The component listens only to its own request, never to the static events.
  • In Audio Source mode the component takes the AudioSource over while it plays: it sets the clip and switches loop off. Word events are raised from audioSource.time against the clip's boundaries. Finished is raised when the clip has played to its end.
  • Stop() ends a playback; pausing the AudioSource yourself (AudioSource.Pause()) does not end it, and the component waits.
  • Finished is raised once per Play(), also when it is stopped or fails. OnDisable stops the playback; OnDestroy cancels it and destroys the clips the component owns.
  • In Edit mode the component always speaks directly (the Inspector preview).

SubtitleHighlighter component

Add Component > luanrobs > Subtitle Highlighter. Needs uGUI.

Field Description
Source The SpeechSource to follow. Empty: follow every TextToSpeech.Speak request.
Target UnityText (uGUI legacy Text, default) or TextMeshPro.
Unity Text, Text Mesh Pro The text component to write to; empty means the component of that type on the same GameObject.
Highlight Color Colour of the word being heard.
Clear When Finished Empty the text when the speech ends instead of removing only the highlight.

On Started the component shows the text, on each word it colours that word, and on Finished it clears the highlight. Requests with ssml on are ignored, because their indexes point into markup. The component turns rich text on for the label it writes to.

SpeechRichText.Escape(text, flavor) and SpeechRichText.Highlight(text, start, length, color, flavor) do the escaping and the colouring, for your own labels (UnityText, TextMeshPro or UIToolkit). A < in the spoken text is made harmless, so text such as a < b is shown as typed. The highlighted range is widened so it never splits a surrogate pair or a line break. TextMeshPro needs the TMP Essential Resources for its default font.

Editor preview

In the Windows Editor, the Inspector of a SpeechSource has a Voice pop-up (Default plus the offline voices, shown as Name (Language)), a Refresh voices button, and a Preview button that speaks the text with the options above, in Edit mode and in Play mode. Stop ends it. A status line shows the engine state, the preview's status and the last error. On other Editors the Preview section shows "Preview needs the Windows Editor."

The preview speaks directly through Windows, as Speak does, whatever the Output field says. The Edit-mode engine is dropped when Play mode starts and when it ends, and the preview is cancelled when the Inspector closes.

Refresh voices reads the voice list again by restarting the engine. In Play mode that would stop every Speak and Synthesize of the game, so there the button only starts the engine when it is not initialized or has failed; while it is ready the button is disabled and the Inspector says "Exit Play mode to reload the voice list".

GameObject > Audio > Speech Source (luanrobs) creates a GameObject with the component under the selected object (inside the prefab root in Prefab Mode). Tools > luanrobs > Text to Speech > Documentation opens the online manual, only when you click it.

Error handling

Invalid arguments throw. A null text, or a null language passed to GetVoices, throws ArgumentNullException. An empty or white-space text, or a text longer than 3999 units, throws ArgumentException. A rate, pitch or volume outside its range, a non-finite or non-positive timeout, or a cache capacity below 1 throws ArgumentOutOfRangeException. Nothing changes when a call throws. Calling the API from another thread throws InvalidOperationException.

Everything else does not throw. It arrives as a SpeechError (a Code, an English Message and a NativeCode from the platform) through InitializationFailed, or through Error followed by Finished of the request, whose Status becomes Failed. Commands that cannot apply (Stop with nothing playing, Cancel on a finished request) do nothing. The package logs one warning per failed initialization: [Text to Speech] <code>: <message>, and nothing on success.

Code Meaning and what to do
NotSupported The platform has no backend (iOS, macOS, Linux, WebGL, 32-bit or ARM64 Windows). Check TextToSpeech.IsSupported and show an alternative.
NoEngine The device has no speech engine, or the engine has no voice at all. On Android, install an engine such as Google Speech Services.
InitializationTimeout The engine did not answer within the timeout (default 10 s, Initialize(timeoutSeconds)). Call Initialize again to retry.
InitializationFailed The engine refused to start; read the message. Call Initialize again to retry.
VoiceNotFound voiceId names no installed voice and no language was given.
LanguageNotAvailable No voice allowed by the options speaks the language. Offer another language, or turn offlineOnly off where network voices exist.
VoiceNotInstalled The engine knows a matching voice but its data is not installed (Android). Call OpenInstallVoiceData().
SsmlNotSupported ssml was set on Android.
NetworkError The engine needed the network and could not reach it (Android network voices).
OutputError Audio could not be played or written, or Unity could not create the clip. With Speak on Windows, this includes a machine with no audio output device.
InvalidAudio The engine produced audio the package cannot read.
EngineError The engine reported a failure; NativeCode has the platform code. On Android this includes an engine that stopped responding and an engine whose process ended (the package starts it again; see Android).

A request made while the state is Failed is accepted and fails with the stored initialization error on the next frame; nothing retries on its own. A request made while the state is NotInitialized starts the engine first.

Platform support

Platform What happens Options Events
Windows 64-bit, player and Editor Windows voices; Speak plays through Windows; Synthesize gives a clip. All, including ssml. Word timings from the engine.
Android The device's engine; Speak plays through the engine; Synthesize gives a clip. All except ssml (fails with SsmlNotSupported). Word timings on API 26 and newer when the engine reports them.
iOS, macOS, Linux, WebGL, 32-bit and ARM64 Windows NotSupported. None. InitializationFailed, and Error plus Finished for each request.

The backend is chosen once, when the engine starts. Branch on TextToSpeech.IsSupported, which is true on 64-bit x64 Windows (player and Editor) and on Android players. In the Windows Editor with the Android build target, the Windows backend is used, because the Editor runs on Windows.

Tested on

This table lists everything that was run for version 1.0.0. The README has a short version. A platform that is not listed, or a row that says not run or pending, was not run. Nobody listened to the audio: it was measured by script (sample rate, level, length, pitch, and the energy after each word boundary). Only pt-BR voices (Microsoft Maria and Microsoft Daniel) were installed on the test machine, so speech in other languages was not run.

Platform Status
Windows Editor, Unity 6000.3.12f1 Run on Windows 11 (2026-10-21): 281 of 281 EditMode tests and 21 of 21 PlayMode tests passed in the development project and again in a clean project with the package installed from a .tgz archive and the Demo sample imported. A Domain Reload check (three Play sessions with Domain Reload disabled) passed.
Windows Editor, Unity 6000.0.84f1 Run on Windows 11 (2026-10-21) in a clean project with the package installed from the archive: 281 of 281 EditMode tests and 21 of 21 PlayMode tests passed.
Windows player (Mono), Unity 6000.3.12f1 and 6000.0.84f1 Run on Windows 11 (2026-10-21): a test driver walked the five demo scenes, synthesized with both installed voices and passed, from the development project (6000.3.12f1) and from the clean projects (both versions).
Windows player (IL2CPP), Unity 6000.3.12f1 Run on Windows 11 (2026-10-21): the same test driver passed.
Android API 26 (8.0), x86_64 emulator with Google APIs, Unity 6000.0.84f1 build Run 2026-10-21, IL2CPP: the image has one TTS engine, Google's (com.google.android.tts, 218 voices listed). The test driver walked the five scenes and passed. Synthesize gave clips with estimated word timings (the engine sent no ranges for files); Speak with the first voice (fi-FI) raised no word events, while the subtitles scene's Speak raised 23. Stopping the engine's process (am force-stop) during a Speak ended it with EngineError after 1.5 s, and the next Synthesize completed. Not run on a physical device.
Android API 36 (16), x86_64 emulator with Google Play, Unity 6000.3.12f1 build Run 2026-10-21, IL2CPP: Google's engine (com.google.android.tts, 473 voices listed). The test driver passed: Speak raised 9 of 9 word events; Synthesize clips had estimated word timings. Stopping the engine's process during a Speak ended it with EngineError after 2.2 s, and the next Synthesize completed; the same after a stop while idle. Not run on a physical device.
Windows 10 not run
Windows with an English or other non-pt-BR voice not run
Android API 23 to 25, ARM64 devices not run
Android physical device, Android engines other than the emulator's not run
Other platforms (macOS, Linux, iOS, WebGL and the rest) not run

Windows

What is used. Windows.Media.SpeechSynthesis for voices, rendering and word cues, and Windows.Media.Playback.MediaPlayer for Speak, both through C++/WinRT inside Runtime/Plugins/Windows/x86_64/LuanrobsSpeech.dll. C# never touches COM, so Mono and IL2CPP behave the same. SAPI is not used.

Voices. The list is the "OneCore" voices of Settings > Time & language > Speech. Voices arrive with the Windows language packs: add a language under Settings > Time & language > Language & region, install its speech feature, and its voices appear. The older SAPI desktop voices are not listed. Windows reports each voice's gender and language.

Behaviour.

  • Speak plays through Windows, not through Unity: AudioListener volume, pause and Audio Mixer do not apply to it. Use Synthesize and an AudioSource for that.
  • Word events during Speak are the engine's cues, in real time. SSML is passed unchanged, so word indexes then refer to the SSML string.
  • Initialization does not block the calling thread. The first call loads the DLL (a few milliseconds) and returns; Windows lists the voices on a thread of the DLL and Initialized follows on a later frame (about 30 ms here; up to the Initialize timeout on a slow machine).
  • Speak renders the whole text before it plays: about 0.2 to 0.5 seconds for one sentence in the measurements here, longer for long texts. Each queued Speak is rendered when it reaches the head of the queue, so consecutive queued sentences have that gap between them.
  • Speak and Synthesize render on two separate threads of the DLL, so a Speak does not wait for a long Synthesize (measured: a short Speak started 0.3 s after a 3995-unit Synthesize at rate 0.5 was requested, while that Synthesize ended after 3.9 s).
  • Speak volume uses the engine's own curve; Synthesize volume is linear.
  • Without an audio output device, Speak fails with OutputError.
  • Rate, pitch and volume need Windows 10 version 1709 or newer. That path was not run on Windows 10.

The DLL. 64-bit only; the package reports NotSupported on 32-bit and ARM64 Windows. It is a Windows x64 plugin for the Editor and the Standalone Win64 player. It imports only system DLLs that every Windows 10 and 11 installation has and links the C/C++ runtime statically, so players need no Visual C++ redistributable. Its source, export list, version resource and build.bat are in Native~/Windows with a README that explains how to rebuild it; the package is read-only when installed from the Asset Store, so copy it into your project's Packages folder first. Close the Editor before replacing the DLL.

Android

What is used. android.speech.tts.TextToSpeech, through SpeechBridge.java in Runtime/Plugins/Android/LuanrobsSpeech.androidlib. Unity compiles it with Gradle when you build; there is no .aar and no .so. A Java class is needed because the progress callbacks (UtteranceProgressListener) are an abstract class.

Setup. None. The library manifest declares that the app queries text-to-speech services (android.intent.action.TTS_SERVICE) and, for the voice data screen, android.speech.tts.engine.INSTALL_TTS_DATA, which Android's package visibility rules need on apps that target API 30 or newer. It adds no permission. The bridge keeps temporary .wav files in <cache dir>/luanrobs-speech/, deletes them when a request ends and removes stale ones at start.

Engine and voices.

  • The default engine is the one the system uses. TextToSpeech.Engines lists the installed engines, CurrentEngine the one in use, and TextToSpeech.Initialize(timeoutSeconds, engine) starts a specific engine by its package name. A different engine restarts the connection.
  • Voices come from getVoices(): the id is the voice name, Gender is always Unknown, and RequiresNetwork, IsInstalled and Quality come from the engine. With offlineOnly (the default) network voices and voices whose data is not installed are not chosen.
  • A language the device has no voice for fails with LanguageNotAvailable. If the engine lists the voice but its data is missing, the error is VoiceNotInstalled. TextToSpeech.OpenInstallVoiceData() opens the engine's voice data screen when you call it and returns false when nothing could be opened. The package never opens it on its own. When the user returns, call TextToSpeech.Shutdown() and TextToSpeech.Initialize() to read the new voices (the Demo does this).
  • If the device has no engine, initialization fails with NoEngine.

Behaviour.

  • The bridge uses two TextToSpeech instances on the same engine, one for Speak and one for Synthesize, so rendering a clip does not interrupt speech. The engine may still run them one after the other, so a Synthesize can wait behind a long Speak.
  • When the engine stops. If the engine's process ends while the app runs (the engine is updated, or Android reclaims its memory), the bridge is told that the engine's service disconnected; two refusals in a row count the same. The requests in flight end with EngineError ("The speech engine stopped (its process ended); Text to Speech is starting it again, so the next request can succeed."), the package connects to the engine again, and requests made meanwhile wait and then go to it. If the engine cannot be started again within 20 seconds, those requests and every later one fail with an EngineError that says to call TextToSpeech.Shutdown() and then Initialize(). The voice list stays the one read at initialization.
  • Speak plays through the engine: Unity's audio settings do not apply.
  • Word events need API 26 and an engine that reports ranges. Otherwise Speak raises none, and Synthesize clips get estimated timings.
  • SSML is not supported.
  • A request that produces no sign of life for 30 s + 0.15 s per character / rate ends with EngineError ("The speech engine stopped responding.").
  • When the application is paused, speech stops if StopOnPause is true.
  • Volume: the package scales the samples of a synthesized clip itself.

Domain Reload

The package supports Enter Play Mode Options with Domain Reload disabled. Static state is reset when Play mode starts, and again before an assembly reload: the engine connection, voices, queues, every static event subscriber, and StopOnPause (back to true). Consequences:

  • Subscribe to TextToSpeech events in Start or OnEnable (not in a static constructor or [InitializeOnLoad]), and unsubscribe in OnDisable. A subscription made before Play mode starts is dropped.
  • The engine is created again on the first request of each Play session.
  • The hidden object [luanrobs Text to Speech] (hidden in the Hierarchy, kept across scene loads) drives the package's Update. It is destroyed when Play mode ends.
  • In Edit mode, the Inspector preview runs from EditorApplication.update instead. The Edit-mode engine is dropped when Play mode starts and when it ends.
  • On Windows the native DLL stays loaded across reloads; the package resets its queues at the start of each session.

Memory notes

  • A rendered clip lives in memory until you destroy it (or until the cache evicts it). Speech at 16 kHz mono 16 bit is about 32 KB per second; Android engines may produce a higher sample rate.
  • Nothing is streamed and nothing is kept on disk by the Windows backend. The Android bridge writes a temporary .wav per Synthesize request into the app cache and deletes it when the request ends.
  • Use SpeechClipCache for lines that repeat and a small Capacity for lines that do not.
  • A long Synthesize is turned into a clip in the frame its audio arrives. Measured in the Windows Editor (Unity 6000.3.12f1 and 6000.0.84f1) for a 3995-unit text: at rate 1 (398 s of audio, 6.4 million samples) that frame took 85 to 230 ms; at rate 0.5 (795 s, 12.7 million samples, a 48.5 MiB float clip) 140 to 430 ms, the higher values with two Editors running at once; with the WAV bytes, the decoded samples and the clip in memory at the same time (about 100 MiB at the peak). On Android the WAV file is also read in that frame. For narration, synthesize sentence by sentence.
  • While nothing is in flight, the Android backend makes no call into Java per frame; it queries the bridge only while the engine is starting or a request is running.

Limitations

These are known and stated up front.

  • Windows 64-bit and Android only. iOS, macOS, Linux, WebGL, 32-bit Windows and ARM64 Windows report NotSupported.
  • Voices belong to the device. A language can be missing, and the package does not download or bundle voices. It does not use cloud, neural or online voices.
  • No SSML on Android. On Windows the SSML is passed through unchanged; the package does not validate it.
  • 3999 UTF-16 units per request, and the whole text is rendered before it plays.
  • No pause and resume, no streaming synthesis, no speech recognition, no lip-sync or visemes, and no voice list window in the Editor.
  • Speak is outside Unity's audio. Mixers, AudioListener volume and pause do not reach it. Use Synthesize for that.
  • Rate and pitch differ per engine. The same value sounds different on Windows and on an Android engine.
  • Android word events depend on API 26 and on the engine.
  • Main thread only.
  • Generated speech rights. The voices belong to Microsoft or to the device maker or engine vendor. Whether you may record and redistribute their output is set by their terms; the package does not grant those rights.

API reference

Namespace: Luanrobs.Speech. Assembly: Luanrobs.Speech.

If your scripts live in an assembly definition, add a reference to Luanrobs.Speech.

TextToSpeech

public static class TextToSpeech

Member Description
const int MaxTextLength 3999 UTF-16 units.
const float DefaultTimeout 10 seconds.
bool IsSupported True on 64-bit x64 Windows and Android players.
SpeechState State, bool IsReady, SpeechError InitializationError Engine state: NotInitialized, Initializing, Ready, Failed.
IReadOnlyList<SpeechVoice> Voices, SpeechVoice DefaultVoice Voices of the engine, once Ready.
IReadOnlyList<SpeechEngine> Engines, SpeechEngine CurrentEngine Installed engines (Android) and the one in use.
bool IsSpeaking, bool IsBusy A Speak request is running; any request is queued or running.
bool StopOnPause Stop speech when the application is paused. Default true.
event Action Initialized, event Action<SpeechError> InitializationFailed Engine start outcomes.
event Action<SpeechUtterance> Started, Finished; event Action<SpeechUtterance, SpeechWordBoundary> WordBoundary; event Action<SpeechUtterance, SpeechError> Error Request events.
void Initialize(float timeoutSeconds = 10, string engine = null) Starts the engine. No effect when already initializing or ready with the same engine.
void Shutdown() Stops every request and disconnects.
IReadOnlyList<SpeechVoice> GetVoices(bool offlineOnly = true), GetVoices(string language, bool offlineOnly = true) A new list each call.
SpeechVoice ResolveVoice(SpeechOptions options = null) The voice a request would use; null when not Ready.
SpeechUtterance Speak(string text, SpeechOptions options = null) Speaks.
SpeechUtterance Synthesize(string text, SpeechOptions options = null) Renders an AudioClip.
void Stop(), void StopAll() Stop Speak requests; stop every request.
bool OpenInstallVoiceData() Android: opens the engine's voice data screen. Returns false elsewhere or when it cannot open.

SpeechUtterance

public sealed class SpeechUtterance : CustomYieldInstruction

Member Description
Id, Kind, Text, Options Request id (unique, from 1), Speak or Synthesize, the text, a copy of the options.
Voice, Status, IsDone, FromCache, Error The voice chosen (set when the request starts), Queued/Running/Completed/Stopped/Failed, whether it is over, whether it came from a cache, the error.
Clip, Duration, WordBoundaries The AudioClip of a completed Synthesize request, its length, and the word timings.
event Started, WordBoundary, Finished Events of this request.
void Cancel() Ends the request.
int WordIndexAt(float seconds) Index of the word heard at that time; -1 before the first.

Getters can be read from any thread (values may be a frame old); Cancel and the events belong to the main thread. WordBoundaries returns an immutable snapshot: enumerating it on another thread while words arrive is safe, and reading the property again gives the newer words.

SpeechOptions, SpeechVoice, SpeechEngine, SpeechError, SpeechWordBoundary

Described in Options, Voices and languages and Word events and timings. SpeechEngine has Id (Android: the package name; Windows: Windows.Media.SpeechSynthesis), Name and IsDefault. SpeechError has Code, Message and NativeCode. SpeechOptions also has Clone() and Validate(), and the constants MinRate, MaxRate, MinPitch and MaxPitch.

SpeechClipCache

public sealed class SpeechClipCache : IDisposable: SpeechClipCache(int capacity = 32), Capacity, Count, GetOrSynthesize(text, options), TryGet(text, options, out clip, out wordBoundaries), Clear(), Dispose().

SpeechSource

public sealed class SpeechSource : MonoBehaviour: Text, TextAsset, EffectiveText, Options, Output, AudioSource, PlayOnEnable, CacheClips, IsPlaying, Current, OnStarted, OnWord, OnFinished, OnError, Started, WordReached, Finished, Play(), Play(string), Stop().

SubtitleHighlighter

public sealed class SubtitleHighlighter : MonoBehaviour (needs uGUI): Source, TextTarget, UnityText, TextMeshPro, HighlightColor, ClearWhenFinished, ShownText, Show(string), Highlight(int start, int length), ClearHighlight().

SpeechRichText

public static class SpeechRichText: Escape(string, SpeechTextFlavor), Highlight(string, int start, int length, Color, SpeechTextFlavor).

Enums

SpeechState, SpeechGender, SpeechQueueMode (Enqueue, Interrupt), SpeechKind, SpeechStatus, SpeechErrorCode, SpeechOutputMode (Speak, AudioSource), SpeechTextFlavor (UnityText, TextMeshPro, UIToolkit).

Troubleshooting and FAQ

There are no voices, or Voices is empty

TextToSpeech.Voices is filled only when State is Ready; wait for Initialized. If it is Ready and still empty on Windows, install a language with its speech feature in Settings > Time & language. On Android, check InitializationError (NoEngine), install an engine such as Google Speech Services, and make sure its voice data is installed. By default only installed voices that work offline are listed: GetVoices(false) shows the others.

LanguageNotAvailable or VoiceNotInstalled

The device has no matching offline voice. On Windows add the language and its speech pack. On Android call TextToSpeech.OpenInstallVoiceData() to open the engine's voice data screen, then Shutdown() and Initialize() when the user comes back. Offer a fallback language in your game.

Nothing is heard

Check the device volume first. Speak plays through the operating system, so Unity's AudioListener volume and pause do not matter; Synthesize plays through your AudioSource, so they do. With Speak on Windows, a machine with no audio output device reports OutputError. In the Editor, Speak plays through Windows even when Unity's audio is muted. Check TextToSpeech.State, the Error event and the Console warning [Text to Speech] ....

The first sentence starts late

The whole text is rendered before it plays, and the engine starts on the first request. Call TextToSpeech.Initialize() early, split long texts by sentence, and use a SpeechClipCache for lines you know in advance.

NotSupported

The platform is not Windows x64 or Android, or it is an ARM64 or 32-bit Windows build. TextToSpeech.IsSupported tells you before you ask. Nothing else is needed for the package to compile on those platforms.

NoEngine on Android

The device has no text-to-speech engine, or the engine has no voice. Install an engine in the system settings (for example Google Speech Services). On devices without Google services, an OEM engine may be available.

Word events are missing on Android

They need API 26 and an engine that reports ranges. Synthesize clips still carry estimated timings (IsEstimated).

Handlers do not run after I enter Play mode again

Static subscribers are dropped when Play mode starts. Subscribe in Start or OnEnable.

The Editor says the DLL cannot be replaced or reports a version mismatch

The Editor keeps LuanrobsSpeech.dll loaded. Close the Editor, update the package, then reopen it.

The highlighter shows tags or the wrong word

Use text without your own rich-text tags in the label, or let the highlighter write the label (it escapes <). Requests with ssml are ignored by the highlighter, because their indexes point into the SSML.

Can I record the speech and ship it as audio files?

Whether you may is set by the terms of the voice's vendor (Microsoft, the device maker or the engine vendor). The package renders at run time and does not grant those rights.

Support

Email: luanrobs@gmail.com

When reporting a problem, please include your Unity version, the platform (device model and OS version, Windows build number), the Console, Logcat or Player log output, and the output of TextToSpeech.State, InitializationError and Voices.

Online: https://luanrobs.com/text-to-speech/

I maintain and support this package myself. If it saves you time, a review on the Asset Store helps a lot. Thank you.