> ## 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.

# Godot: speech

> Written lines with LokutorVoice (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 Godot

Not every character needs a conversation. `LokutorVoice` 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 a **LokutorVoice** node to the character (a `Node3D`: the head is a good place), pick its **Voice** and **Language**, and:

```gdscript theme={null}
extends Node3D

@onready var guard: LokutorVoice = $Guard/Head/LokutorVoice

func _ready() -> void:
    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!", {"interrupt": true})     # now, dropping what is being said
    guard.say("[sigh] Fine.", {"voice": "M3"})        # another voice for one line
```

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

It finds a [LokutorLipSync](https://docs.lokutor.com/sdks/godot/lip-sync.md) beside it, and can share one with a LokutorAgent.

### Lines are kept

Each line is made once and kept in **Cache Dir** (`user://lokutor_voices`) with its mouth shapes: said again, it starts at once and costs nothing. Fetch the ones you know are coming:

```gdscript theme={null}
await guard.preload_lines(["Halt!", "Pass, friend.", "Nice hat."])
print(guard.has_line("Halt!"))
```

### Ship them with the game

Lines recorded into the project need no network, no key and no money while people play. Run this once from a tool script or a scene of your own:

```gdscript theme={null}
await guard.save_lines_to("res://voices", ["Halt!", "Pass, friend.", "Nice hat."])
```

Then set **Cache Dir** to `res://voices` and add `*.lokvoice` to the export preset's **Filters to export non-resource files**. 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 `ticket_provider`, as for an [agent](https://docs.lokutor.com/sdks/godot/introduction.md#shipping).

## Text to speech

`LokutorTTSClient` is the request itself:

```gdscript theme={null}
extends Node

func _ready() -> void:
    var tts := LokutorTTSClient.new()
    tts.api_key = OS.get_environment("LOKUTOR_API_KEY")
    add_child(tts)
    var got: Dictionary = await tts.synthesize("The gate is open.", {"voice": "M2", "language": "en", "visemes": true})
    if got.ok:
        var wav := FileAccess.open("user://gate.wav", FileAccess.WRITE)
        wav.store_buffer(LokutorAudio.wav_bytes(got.audio, got.sample_rate))
    else:
        push_warning(str(got.error))
```

* Audio is 16-bit PCM, 44.1 kHz, mono. `audio` and `visemes` signals (or the `on_audio` and `on_visemes` options) carry it as it is made; the result has all of it.
* Requests run one after another, and the connection stays open a few seconds (`keep_open_seconds`) so the next one skips the handshake. While open it counts as a [session](https://docs.lokutor.com/pricing.md#limits).
* `cancel()` stops everything; with the `ticket` you gave a request, only that one.
* Options: `voice`, `language`, `speed`, `temperature`, `dictionary_ids`, `pronunciations`... ([Text to speech](https://docs.lokutor.com/sdk/tts.md)).

To play it as it arrives use a `LokutorVoicePlayer`, which also has the clock for lip sync:

```gdscript theme={null}
extends Node3D

@onready var tts: LokutorTTSClient = $LokutorTTSClient
@onready var player: LokutorVoicePlayer = $LokutorVoicePlayer

func speak(text: String) -> void:
    player.begin(player.generation + 1)
    await tts.synthesize(text, {"on_audio": func(pcm): player.push(pcm)})
```

## Speech to text

`LokutorSpeechToTextClient` transcribes the microphone as the player talks: voice commands, dictation, captions. There is no language model behind it.

```gdscript theme={null}
extends Node

func _ready() -> void:
    var ears := LokutorSpeechToTextClient.new()
    ears.api_key = OS.get_environment("LOKUTOR_API_KEY")
    ears.language = "en"
    ears.keyterms = ["Oakvale", "Brom", "fireball"]
    ears.partial_transcript.connect(func(text): $Caption.text = text)
    ears.final_transcript.connect(_on_command)
    add_child(ears)
    if not await ears.open():
        push_warning("Could not start listening.")

func _on_command(text: String) -> void:
    if text.to_lower().contains("fireball"):
        $Wizard.cast("fireball")
```

`keyterms` are the names recognition would not know ([Custom vocabulary](https://docs.lokutor.com/guides/custom-vocabulary.md)). `end_utterance()` finishes what is being said now, for a push-to-talk key. With `use_microphone` off you send the audio yourself with `send_audio()`: 16-bit PCM, 16 kHz, mono, silences included.

`LokutorSTTClient` transcribes one whole recording:

```gdscript theme={null}
func transcribe(path: String) -> String:
    var stt := LokutorSTTClient.new(OS.get_environment("LOKUTOR_API_KEY"))
    var got: Dictionary = await stt.transcribe(FileAccess.get_file_as_bytes(path), {"language": "en"})
    return got.text if got.ok else ""
```

## A conversation without a character

`LokutorVoiceAgentClient` is the protocol alone, with the names of the [JavaScript SDK](https://docs.lokutor.com/sdks/javascript/reference.md) (`connect` and `disconnect` are `open` and `close`, because every Godot object already has the other two). Use it for a narrator, a companion app or a UI of your own:

```gdscript theme={null}
extends Node

func _ready() -> void:
    var agent := LokutorVoiceAgentClient.create({
        "api_key": OS.get_environment("LOKUTOR_API_KEY"),
        "prompt": "You are the ship's computer. One short sentence each time.",
        "voice": "F4",
        "on_response": func(text): $Log.text += text + "\n",
    })
    agent.error.connect(func(err): push_warning(str(err)))
    add_child(agent)
    if await agent.start_managed():          # the microphone and the speaker too
        await get_tree().create_timer(60.0).timeout
        print(agent.get_transcript_text())
        agent.close()
```

## Your own model

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

```gdscript theme={null}
func _ready() -> void:
    oracle.on_llm_request = _answer
    oracle.start_conversation()

func _answer(messages: Array, _tools: Array, reply: LokutorVoiceAgentClient.LlmReply) -> void:
    var said: String = messages[-1].get("content", "")
    for sentence in $Riddles.answer_to(said):
        if reply.cancelled:
            return                       # the player spoke over it
        reply.chunk(sentence + " ")      # Lokutor starts speaking at the first sentence
```


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