Text-to-Speech (TTS)

Dynamic character speech: text goes in, spoken 3D audio plus a lipsync timeline comes out. TGorillaTextToSpeech sits on top of the audio stack and never touches an audio API itself — which is why it works with FMOD and OpenAL alike.

The speech engine is not part of the Gorilla3D distribution. Piper and its voice models are downloaded separately, see Getting Piper.

Table of Contents

Architecture

TGorillaTextToSpeech          component: characters, queue, cache, lipsync
        |
        +-- TGorillaTTSEngine        exchangeable backend (Piper, ...)
        |
        +-- TGorillaAudioManager     playback (OpenAL / FMOD)

Speak() does not block. Synthesis runs on a worker thread, playback starts as soon as the audio is ready, and several sentences per character are spoken in order.

Units

Unit Content
Gorilla.Audio.TTS Request, result, abstract TGorillaTTSEngine, engine registry
Gorilla.Audio.TTS.Speaker TGorillaTextToSpeech, TGorillaTTSSpeaker, cache, worker thread
Gorilla.Audio.TTS.Piper Piper backend (process or HTTP mode)
Gorilla.Audio.TTS.Visemes Viseme set, timeline, phonemizer, estimator
Gorilla.Audio.TTS.Espeak Phonemizer using the espeak-ng library (preferred)
Gorilla.Audio.TTS.Utils Process runner, RIFF/WAVE tools, amplitude envelope

Getting Piper

Piper is a local neural text-to-speech system — no cloud, no account, no per-request cost. It consists of an executable and one voice model per voice. Both are obtained from the Piper project, not from Gorilla3D.

1. The Piper executable

Source
Project https://github.com/rhasspy/piper
Releases https://github.com/rhasspy/piper/releases

The backend was tested against rhasspy/piper 1.2.0, whose command line matches the default CommandTemplate. Archives are available for Windows amd64, Linux x86_64 / aarch64 / armv7l and macOS x64 / aarch64.

Unpack the archive next to your application. You get a folder piper/ containing piper.exe (respectively piper) and the espeak-ng-data folder.

2. Voice models

Voices are not contained in the executable archives and have to be downloaded separately:

Source
Voice models https://huggingface.co/rhasspy/piper-voices
Listen before downloading https://rhasspy.github.io/piper-samples/

Every voice consists of two files that belong together:

de_DE-thorsten-medium.onnx
de_DE-thorsten-medium.onnx.json

The .json holds the model configuration, including the sample rate and the speaker list of multi-speaker models. A model without its .json cannot be used.

3. espeak-ng (optional, for better lipsync)

The Piper archives already ship espeak-ng.dll (libespeak-ng.so.1 / libespeak-ng.dylib), which the phonemizer picks up automatically. Only when you want the phonemizer without Piper — or a newer version — fetch it from https://github.com/espeak-ng/espeak-ng.

Licensing

Piper is MIT licensed, espeak-ng is GPL. The voice models carry their own licenses (mostly CC-BY or public domain) — check the license of every voice you ship. Since none of it is redistributed by Gorilla3D, the obligations are between you and the respective project.

Setting up the Engine

uses
  Gorilla.Audio.Manager, Gorilla.Audio.OpenAL,
  Gorilla.Audio.TTS, Gorilla.Audio.TTS.Speaker, Gorilla.Audio.TTS.Piper;

var LPiper : TGorillaPiperEngine;
begin
  LPiper := TGorillaPiperEngine.Create(Self);
  LPiper.ExecutablePath := 'C:\tools\piper\piper.exe';  // or just 'piper' (PATH)
  LPiper.ModelDirectory := 'C:\tools\piper\voices';     // scanned for *.onnx
  LPiper.DefaultVoice   := 'de_DE-thorsten-medium';

  GorillaTextToSpeech1.AudioManager := GorillaOpenALManager1;
  GorillaTextToSpeech1.Engine       := LPiper;
end;

With the standard layout you can skip all of that: when ExecutablePath and ModelDirectory are left empty, the engine searches next to the application for piper\piper.exe, piper.exe and Piper\piper\piper.exe, and for the voice folders piper\voices, voices and models.

GetVoices() then lists everything it found; multi-speaker models report each speaker separately as model.onnx#3. ResolveExecutable() tells you which executable would actually be called — an empty result means Piper was not found.

If your Piper version expects a different command line, only CommandTemplate needs adjusting. Placeholders: %EXE%, %MODEL%, %OUTPUT%, %LENGTH_SCALE%, %NOISE_SCALE%, %NOISE_W%, %SENTENCE_SILENCE%, %SPEAKER%, %ESPEAK_DATA%, %CUDA%.

Property Default Description
Mode pmProcess Spawn the executable, or talk to an HTTP server
ExecutablePath — Path or bare name of the Piper executable
ModelPath — Model used when nothing else names one
ModelDirectory — Folder scanned for *.onnx
EspeakDataPath — Only needed when Piper cannot find its espeak data
CommandTemplate see above Command line of the executable
Timeout 30000 Milliseconds a single synthesis may take
NoiseW 0.8 Variation of the phoneme lengths
CudaEnabled False Adds --cuda to the command line
ServerUrl http://127.0.0.1:5000 Base address in HTTP mode
HttpPath — Resource path appended to ServerUrl

HTTP Mode

Instead of spawning a process per sentence, the engine can talk to a running Piper HTTP server. This is the only mode available on mobile platforms, and it is the better choice when many characters speak at once, because the model stays loaded:

LPiper.Mode      := pmHttp;
LPiper.ServerUrl := 'http://127.0.0.1:5000';

Making Characters Speak

var LSpeaker : TGorillaTTSSpeaker;
begin
  TTS.AudioManager := GorillaOpenALManager1;
  TTS.Engine       := GorillaPiperEngine1;

  LSpeaker := TTS.AddSpeaker('Guard', 'de_DE-thorsten-medium');
  LSpeaker.Target  := GuardModel;   // the voice comes out of the model
  LSpeaker.Pitch   := 0.92;         // same model, different character
  LSpeaker.Spatial := true;

  TTS.Speak('Guard', 'Halt! Who goes there?');
end;

A character is addressed by name, so gameplay code never needs a reference to the speaker object. FindSpeaker() returns it when you do.

TTS.Speak(LSpeaker, 'Move along.');    // already resolved speaker
LSpeaker.Stop();                        // stop and clear this character's queue
LSpeaker.Pause();
LSpeaker.Resume();
TTS.StopAll();                          // silence everybody

With Speaker.Interrupt := true a new sentence cuts off the running one instead of queueing behind it — the right setting for combat barks, the wrong one for dialogue.

Speaker Settings

Property Description
Name The name the character is addressed by
VoiceId Piper model name or path; empty uses the engine's default voice
SpeakerId Speaker index inside a multi-speaker model, -1 = default
Language Language of the text, drives phonemization
Rate Speaking rate, 1.0 normal, 1.2 = 20 % faster
Pitch Playback pitch, 1.0 unchanged
Volume Playback gain
Expressiveness Amount of variation in the generated voice, 0..1
SentenceSilence Pause between two sentences in seconds
Enabled A disabled speaker silently drops every Speak()
Spatial Plays the voice at the position of Target instead of centred
Interrupt New sentence cuts off the running one
Target The TControl3D the voice is emitted from
Offset Mouth offset relative to the target's origin
MinDistance, MaxDistance Distance range the voice is attenuated in

Read-only state: IsSpeaking, QueueLength, Current, PlaybackTime, Viseme, VisemeWeights, VisemeWeight[], WordIndex.

Deriving several characters from a single voice model is mostly a matter of Pitch and Rate — two guards at 0.92 and 1.06 are perceived as two people.

Lipsync and Visemes

During playback every speaker reports its current mouth state:

procedure TForm1.OnViseme(ASender : TObject; const ASpeaker : TGorillaTTSSpeaker;
  const AViseme : TGorillaVisemeKind; const AWeights : TGorillaVisemeWeights);
var LKind : TGorillaVisemeKind;
begin
  for LKind := Low(TGorillaVisemeKind) to High(TGorillaVisemeKind) do
    GuardModel.SetMorphTargetWeight(GORILLA_VISEME_NAMES[LKind], AWeights[LKind]);
end;

The viseme set follows the Oculus/Meta LipSync standard (sil PP FF TH DD kk CH SS nn RR aa E I O U), which most character assets ship as blend shapes. For cartoon rigs, GorillaVisemeToMouthShape() maps onto the Preston Blair chart A..H.

The weights are already blended (co-articulation) and always sum to 1.0. OnWord additionally reports word boundaries, for subtitles for example.

How the timings are produced

Piper does not report phoneme times, so the timeline is estimated:

  1. Text is turned into a phoneme sequence (espeak-ng when available, otherwise the rule-based phonemizer for DE/EN).
  2. Each phoneme gets a class-dependent base duration — vowels long, plosives short.
  3. An amplitude envelope is computed from the generated WAV and the speech pauses are detected in it.
  4. The phoneme sequence is distributed over the detected speech sections, using the pauses as anchors. That keeps the mouth in sync even for long sentences.

Phonemizers

Three implementations exist and are chosen by priority — the first available one wins:

Priority Implementation Note
100 TGorillaEspeakLibPhonemizer espeak-ng library directly, real IPA, no process start
50 TGorillaEspeakPhonemizer espeak-ng as a command line tool
0 TGorillaRuleBasedPhonemizer Grapheme approximation for DE/EN, always available

The library variant activates automatically as soon as Gorilla.Audio.TTS.Piper is used, because the Piper releases ship espeak-ng.dll. It is architecture bound: the official archives are 64 bit, so a Win32 build falls back to the rule-based phonemizer.

Custom implementations plug in through IGorillaPhonemizer plus GorillaRegisterPhonemizer() (with a priority), or hard-wired through GorillaSetDefaultPhonemizer().

The Speech Cache

Character speech repeats a lot — greetings, hints, combat barks. CacheEnabled serves anything already known without synthesis latency; with CacheDirectory the cache survives a restart of the program (WAV plus .vis files).

Property Default Description
CacheEnabled True Reuse the audio of sentences spoken before
CacheDirectory — Folder for the persistent cache; empty = memory only
CacheCapacity 64 Number of sentences kept in memory

ClearCache() empties the memory cache, PurgeCache() deletes the files as well.

Events

Both the component and each speaker expose the same set — use the component level for a global subtitle system, the speaker level for one character.

Event Fired when
OnSpeechStart A sentence became audible
OnSpeechFinished A sentence finished playing
OnViseme The dominant mouth shape changed
OnWord The spoken word changed
OnError A sentence could not be spoken

Playback and lipsync are advanced by Update(). AutoUpdate (on by default, UpdateInterval 16 ms) does that from an internal timer; switch it off to drive the component from your own render loop.

Adding Another Engine

type
  TMyEngine = class(TGorillaTTSEngine)
    protected
      function DoSynthesize(const ARequest : TGorillaTTSRequest;
        const AResult : TGorillaTTSResult) : Boolean; override;
    public
      class function GetEngineName() : String; override;
  end;

initialization
  TGorillaTTSEngineRegistry.RegisterEngine(TMyEngine);

DoSynthesize only has to call AResult.SetWave(<RIFF/WAVE stream>). The viseme timeline is estimated automatically afterwards — if the backend reports real phoneme times, it fills AResult.Visemes itself and the estimation is skipped.

Backends that are not thread safe override IsThreadSafe with false; their calls are then serialized.

The engine is selected either through the Engine property or through EngineName (a string such as 'Piper'), in which case the component creates the instance itself.

Platform Support

Mode Windows Linux macOS Android/iOS
Piper pmProcess Yes Yes Yes No (no process spawning)
Piper pmHttp Yes Yes Yes Yes

3D positioning is implemented for OpenAL and FMOD. The module creates the sound item through TGorillaAudioManager.CreateSoundItem(), configures it and loads the audio data afterwards — necessary because FMOD evaluates the 3D mode while creating the sound.

There is no Piper library: piper_phonemize.dll only exports C++-mangled functions with std::vector / std::string parameters, and the actual VITS inference lives inside piper.exe. The only usable parts of the archives are espeak-ng.dll (see Phonemizers) and, in principle, onnxruntime.dll — whose C API would require reimplementing the whole Piper inference.

Troubleshooting

Symptom Cause
ResolveExecutable() returns empty Piper not found — set ExecutablePath
GetVoices() returns nothing ModelDirectory wrong, or the .onnx.json files are missing
Speech is audible but the mouth does not move Blend shape names do not match GORILLA_VISEME_NAMES
Lipsync is coarse Rule-based phonemizer active — check the espeak-ng library, and the bitness of your build
Voice is not positional Spatial off, Target unassigned, or the driver reports Supports3DAudio() = false
First sentence is late, later ones are instant Normal — the cache is doing its job; pre-warm on level load
Nothing at all on Android/iOS pmProcess is unavailable there, use pmHttp

Best Practices

  • Ship neither Piper nor the voices with Gorilla3D — document the download for your users, or fetch it in your installer
  • Pre-warm the cache with recurring lines during loading
  • Give every character its own Pitch/Rate instead of one voice model per NPC
  • Use Interrupt for barks, queueing for dialogue
  • Assign Target so voices are attenuated with distance like every other sound
  • Handle OnError — a missing model is a normal runtime condition
  • Check the license of every voice model you distribute

See Also

API Reference

Related Topics