> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lokutor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Unity: speech

> Written lines with Lokutor Voice (3D voice, lip sync, a queue, lines kept on disk or shipped with the game), and the text-to-speech and speech-to-text clients for Unity and plain C#

Not every character needs a conversation. **Lokutor Voice** says lines you wrote, with the same voices and lip sync, and the clients underneath give you text to speech and speech to text on their own.

## Written lines

**Add Component > Lokutor > Lokutor Voice**, pick its **Voice** and **Language**, and:

```csharp theme={null}
using System.Collections;
using Lokutor;
using UnityEngine;

public class Guard : MonoBehaviour
{
    public LokutorVoice guard;

    async void Start()
    {
        await guard.Say("Halt! Who goes there?");                                 // returns when it has been heard
        _ = guard.Say("Nobody passes.");                                          // waits for the one before
        _ = guard.Say("Behind you!", new SayOptions { Interrupt = true });        // now, dropping what is being said
        _ = guard.Say("[sigh] Fine.", new SayOptions { Voice = "M3" });           // another voice for one line
    }

    IEnumerator Scene()
    {
        yield return guard.SayAndWait("Pass, friend.");                           // in a coroutine
    }
}
```

`Say` returns `true` when the line has been heard, `false` if it could not be said or was stopped. `SayLine(text)` is the same for a UnityEvent. Lines can carry [expression tags](https://docs.lokutor.com/api-reference/expression-tags.md) and be up to 5,000 characters. `onLineStarted` and `onLineFinished` carry the text, for subtitles and gestures; `Error` says what failed.

It uses the character's [Lokutor Lip Sync](https://docs.lokutor.com/sdks/unity/lip-sync.md), and can share it with an agent.

### Lines are kept

Each line is made once and kept on disk (`persistentDataPath/lokutor_voices`) with its mouth shapes: said again, it starts at once and costs nothing. **Keep Lines** turns that off. Fetch the ones you know are coming:

```csharp theme={null}
await guard.PreloadLines(new[] { "Halt!", "Pass, friend.", "Nice hat." });
Debug.Log(guard.HasLine("Halt!"));
```

### Ship them with the game

Lines recorded into the project need no network, no key and no money while people play. Once, in the editor:

```csharp theme={null}
await guard.SaveLinesTo("Assets/Resources/LokutorVoices", new[] { "Halt!", "Pass, friend.", "Nice hat." });
```

**Shipped Lines** (`LokutorVoices`) is the folder, inside a Resources folder, where the component looks for them. A line that changes voice, language or a single word is another line: record it again.

### Shipping the key

A game that makes lines while it runs needs a credential. Set `TicketProvider`, as for an [agent](https://docs.lokutor.com/sdks/unity/introduction.md#shipping).

## Text to speech

`TTSClient` is the request itself, in plain C#:

```csharp theme={null}
var tts = new TTSClient(apiKey);
TTSResult got = await tts.SynthesizeAsync("The gate is open.", new SynthesizeOptions { Voice = "M2", Language = "en", Visemes = true });
if (got.Ok) System.IO.File.WriteAllBytes("gate.wav", LokutorAudio.WavBytes(got.Audio, got.SampleRate));
else Debug.LogWarning(got.Error);
```

* Audio is 16-bit PCM, 44.1 kHz, mono. `OnAudio` and `OnVisemes` carry it as it is made, on the thread that called; the result has all of it.
* Requests run one after another, and the connection stays open a few seconds (`KeepOpen`) so the next one skips the handshake. While open it counts as a [session](https://docs.lokutor.com/pricing.md#limits).
* `Cancel()` stops everything; a `CancellationToken` given to `SynthesizeAsync`, only that one.
* Options: `Voice`, `Language`, `Speed`, `Temperature`, `DictionaryIds`, `Pronunciations`... ([Text to speech](https://docs.lokutor.com/sdk/tts.md)).

## Speech to text

`SpeechToTextClient` transcribes the microphone as the player talks: voice commands, dictation, captions. There is no language model behind it. `LokutorAudioManager` (a component) is the microphone, and raises its events on the main thread:

```csharp theme={null}
using System.Collections.Generic;
using Lokutor;
using UnityEngine;

[RequireComponent(typeof(LokutorAudioManager))]
public class Spells : MonoBehaviour
{
    public string apiKey;
    SpeechToTextClient ears;

    async void Start()
    {
        ears = new SpeechToTextClient(apiKey) { Language = "en", Keyterms = new List<string> { "Oakvale", "Brom", "fireball" } };
        ears.FinalTranscript += text => { if (text.ToLower().Contains("fireball")) Debug.Log("Whoosh"); };
        ears.Error += error => Debug.LogWarning(error.Message);
        if (!await GetComponent<LokutorAudioManager>().StartManaged(ears)) Debug.LogWarning("Could not start listening.");
    }

    void OnDestroy() => ears?.Dispose();
}
```

`Keyterms` are the names recognition would not know ([Custom vocabulary](https://docs.lokutor.com/guides/custom-vocabulary.md)). `EndUtterance()` finishes what is being said now, for a push-to-talk key. With `ConnectAsync()` alone you send the audio yourself with `SendAudio` (16-bit PCM, 16 kHz, mono, silences included) and call `Update()` every frame.

`STTClient` transcribes one whole recording:

```csharp theme={null}
var stt = new STTClient(apiKey);
TranscribeResult got = await stt.TranscribeAsync(System.IO.File.ReadAllBytes("order.wav"), new TranscribeOptions { Language = "en" });
Debug.Log(got.Ok ? got.Text : got.Error.Message);
```

## A conversation without a character

`VoiceAgentClient` is the protocol alone, with the names of the [JavaScript SDK](https://docs.lokutor.com/sdks/javascript/reference.md). Use it for a narrator, a companion app or a UI of your own:

```csharp theme={null}
var agent = new VoiceAgentClient(apiKey, "You are the ship's computer. One short sentence each time.", "F4");
agent.Response += text => Debug.Log(text);
agent.Error += error => Debug.LogWarning(error.Message);
if (await GetComponent<LokutorAudioManager>().StartManaged(agent))          // the microphone and the speaker too
{
    await System.Threading.Tasks.Task.Delay(60000);
    Debug.Log(agent.GetTranscriptText());
    agent.Disconnect();
}
```

Outside Unity, write an `IAudioManager` and call the client's `Update()` every frame. `LokutorSession` is the layer between the two: a character's conversation (states, actions, echo guard, the clock for lip sync) without the engine.

## Your own model

`Llm` points a conversation at an OpenAI-compatible endpoint, and `OnLlmRequest` answers it from the game ([Bring your own LLM](https://docs.lokutor.com/guides/bring-your-own-llm.md)). Both are on the Lokutor Agent too; set them before the conversation starts (`Awake`, or with **Start On Awake** off).

```csharp theme={null}
oracle.OnLlmRequest = async (request, reply) =>
{
    foreach (string sentence in AnswerTo(request.Messages))
    {
        if (reply.Cancelled) break;          // the player spoke over it
        reply.Chunk(sentence + " ");         // Lokutor starts speaking at the first sentence
        await System.Threading.Tasks.Task.Yield();
    }
    return null;
};
oracle.StartConversation();
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.