> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch34-infrastructure/34.4-tts-text-to-speech.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 34.4 TTS (Text-to-Speech)

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~98k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Text-to-Speech (TTS) enables Agent replies to be sent as voice messages to users—particularly useful in mobile chat scenarios. OpenClaw's TTS module (`src/tts/tts.ts`, approximately 1580 lines) supports three Providers, four automatic modes, Agent inline directives for overrides, and automatic summarization for excessively long text.

## 34.4.1 TTS Engine (`src/tts/`)

### Three Provider Architecture

OpenClaw supports three TTS Providers with automatic degradation based on availability:

| Provider       | Type         | Default Model/Voice                      | API Key Source                       |
| -------------- | ------------ | ---------------------------------------- | ------------------------------------ |
| **OpenAI**     | Cloud API    | `gpt-4o-mini-tts` / `alloy`              | `OPENAI_API_KEY` or config           |
| **ElevenLabs** | Cloud API    | `eleven_multilingual_v2` / preset voices | `ELEVENLABS_API_KEY` or `XI_API_KEY` |
| **Edge TTS**   | Free service | `en-US-MichelleNeural`                   | No Key needed (default Provider)     |

> **Sidebar — Edge TTS**
>
> Edge TTS is an unofficial Node.js wrapper (`node-edge-tts` library) around the speech synthesis service built into Microsoft Edge browser. It leverages Microsoft Cognitive Services' online interface, supporting hundreds of languages and voices, requiring no API Key and completely free. Since it requires no configuration, OpenClaw uses it as the default TTS Provider.

The Provider selection priority logic:

```typescript
// src/tts/tts.ts
export function getTtsProvider(config, prefsPath): TtsProvider {
  // 1. User preference (persisted to JSON file)
  const prefs = readPrefs(prefsPath);
  if (prefs.tts?.provider) return prefs.tts.provider;
  
  // 2. Explicitly specified in config file
  if (config.providerSource === "config") return config.provider;
  
  // 3. Auto-detect (prioritize those with Keys)
  if (resolveTtsApiKey(config, "openai")) return "openai";
  if (resolveTtsApiKey(config, "elevenlabs")) return "elevenlabs";
  return "edge";  // fallback
}
```

### Four Automatic Modes

TTS triggering is controlled by `TtsAutoMode`:

| Mode      | Behavior                                                         |
| --------- | ---------------------------------------------------------------- |
| `off`     | TTS completely disabled                                          |
| `always`  | Generate voice for every reply                                   |
| `inbound` | Generate voice reply only when user sends audio/voice message    |
| `tagged`  | Generate only when Agent output contains `[[tts]]` directive tag |

The priority chain for automatic modes is: **Session-level override > User preference file > Config file**.

### Configuration Parsing

`resolveTtsConfig` expands raw YAML configuration into a complete `ResolvedTtsConfig` structure, with all optional fields populated with defaults:

```typescript
export type ResolvedTtsConfig = {
  auto: TtsAutoMode;              // Automatic mode
  mode: TtsMode;                  // "final" final reply only | "all" generate for all
  provider: TtsProvider;
  summaryModel?: string;          // LLM model for summarization
  modelOverrides: ResolvedTtsModelOverrides;  // Directive override strategy
  elevenlabs: { ... };            // ElevenLabs complete config
  openai: { ... };                // OpenAI complete config
  edge: { ... };                  // Edge TTS complete config
  maxTextLength: number;          // Hard limit 4096 characters
  timeoutMs: number;              // API timeout 30 seconds
};
```

### User Preference Persistence

TTS preferences (on/off, Provider, max length, whether to summarize) are persisted via JSON file, default path `~/.config/openclaw/settings/tts.json`. Preference file read/write uses atomic writes (write to temp file then `rename`), preventing concurrent writes from corrupting the file:

```typescript
function atomicWriteFileSync(filePath: string, content: string): void {
  const tmpPath = `${filePath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;
  writeFileSync(tmpPath, content);
  renameSync(tmpPath, filePath);  // atomic replacement
}
```

## 34.4.2 Implementation of Three Providers

### OpenAI TTS

Calls OpenAI's `/v1/audio/speech` endpoint:

```typescript
async function openaiTTS(params): Promise<Buffer> {
  const response = await fetch(`${getOpenAITtsBaseUrl()}/audio/speech`, {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "gpt-4o-mini-tts",    // or tts-1, tts-1-hd
      input: text,
      voice: "alloy",              // 9 voices available
      response_format: "opus",     // opus for Telegram, mp3 for others
    }),
    signal: controller.signal,     // AbortController timeout control
  });
  return Buffer.from(await response.arrayBuffer());
}
```

Supports pointing to custom TTS endpoints via `OPENAI_TTS_BASE_URL` environment variable (such as locally deployed Kokoro, LocalAI). When doing so, whitelist validation for models and voices is automatically relaxed.

**Available voices**: `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer` (9 total).

### ElevenLabs TTS

ElevenLabs provides high-quality voice cloning and multilingual synthesis with the richest API parameters:

```typescript
async function elevenLabsTTS(params): Promise<Buffer> {
  const url = `${baseUrl}/v1/text-to-speech/${voiceId}?output_format=${outputFormat}`;
  const response = await fetch(url, {
    method: "POST",
    headers: { "xi-api-key": apiKey, "Content-Type": "application/json" },
    body: JSON.stringify({
      text,
      model_id: "eleven_multilingual_v2",
      seed: seed,                           // optional: fix random seed
      apply_text_normalization: "auto",     // text normalization mode
      language_code: "en",                  // ISO 639-1 language code
      voice_settings: {
        stability: 0.5,           // 0-1, higher = more stable
        similarity_boost: 0.75,   // 0-1, voice similarity
        style: 0.0,               // 0-1, expressiveness
        use_speaker_boost: true,  // enhance speaker characteristics
        speed: 1.0,               // 0.5-2.0 speech rate
      },
    }),
  });
  return Buffer.from(await response.arrayBuffer());
}
```

### Edge TTS

Edge TTS is the simplest Provider, generating audio directly via the `node-edge-tts` library:

```typescript
async function edgeTTS(params): Promise<void> {
  const tts = new EdgeTTS({
    voice: "en-US-MichelleNeural",
    lang: "en-US",
    outputFormat: "audio-24khz-48kbitrate-mono-mp3",
    rate: "+0%",       // speech rate adjustment
    pitch: "+0Hz",     // pitch adjustment
    volume: "+0%",     // volume adjustment
    proxy: undefined,  // optional HTTP proxy
  });
  await tts.ttsPromise(text, outputPath);
}
```

Edge TTS supports auto-inferring file extension from output format—if the format string contains keywords like `ogg`, `opus`, `webm`, `wav`, it generates files with corresponding extensions. When custom format fails, it automatically falls back to default MP3 format.

### Channel Adaptation

Different chat platforms have different audio format preferences. TTS output format is dynamically adjusted based on the target channel:

| Channel      | OpenAI Format | ElevenLabs Format   | Extension | Voice Compatible    |
| ------------ | ------------- | ------------------- | --------- | ------------------- |
| Telegram     | `opus`        | `opus_48000_64`     | `.opus`   | ✓ (voice bubble)    |
| Others       | `mp3`         | `mp3_44100_128`     | `.mp3`    | ✗ (file attachment) |
| Phone (VoIP) | `pcm` (24kHz) | `pcm_22050` (22kHz) | -         | -                   |

Telegram channel uses Opus encoding because Telegram's voice message bubbles only support OGG Opus format.

## 34.4.3 Agent Inline Directives

Agents can embed `[[tts:...]]` directives in output text to control various parameters of voice synthesis:

### Directive Syntax

**Parameter directive**: `[[tts:key=value key2=value2]]`

```
[[tts:provider=elevenlabs voice_id=pMsXgVXv3BLzUgSXRplE speed=1.2]]
This text will be read using ElevenLabs' specified voice at 1.2x speed.
```

**Text block directive**: `[[tts:text]]...[[/tts:text]]`

```
[[tts:text]]
This is the content to be read, different from the text displayed to users.
[[/tts:text]]
This text will only be displayed to users, not read aloud.
```

### Overridable Parameters

| Directive Key            | Function             | Constraints                   |
| ------------------------ | -------------------- | ----------------------------- |
| `provider`               | Switch Provider      | openai / elevenlabs / edge    |
| `voice` / `openai_voice` | OpenAI voice         | One of 9 preset voices        |
| `voiceId` / `voice_id`   | ElevenLabs voice ID  | 10-40 alphanumeric characters |
| `model` / `modelId`      | Model ID             | Auto-routed by Provider       |
| `stability`              | Stability            | 0-1                           |
| `similarity`             | Similarity boost     | 0-1                           |
| `style`                  | Style expressiveness | 0-1                           |
| `speed`                  | Speech rate          | 0.5-2.0                       |
| `seed`                   | Random seed          | 0-4294967295                  |
| `language`               | Language code        | ISO 639-1 two-letter          |
| `normalize`              | Text normalization   | auto / on / off               |

### Override Strategy

Administrators can use `modelOverrides` configuration for fine-grained control over which parameters Agents are allowed to override:

```yaml
messages:
  tts:
    modelOverrides:
      enabled: true          # master switch
      allowText: true        # allow [[tts:text]]
      allowProvider: true    # allow Provider switching
      allowVoice: true       # allow voice switching
      allowModelId: false    # disallow model switching
      allowVoiceSettings: true
      allowSeed: false
```

## 34.4.4 Long Text Summarization

When an Agent's reply exceeds the maximum length limit (default 1500 characters), the TTS module has two handling strategies:

**1. Summary mode (enabled by default)**: Call an LLM (default uses Agent's main model) to generate a summary not exceeding `maxLength` characters, then convert the summary to speech:

```typescript
async function summarizeText(params): Promise<SummarizeResult> {
  const { ref } = resolveSummaryModelRef(cfg, config);
  const model = resolveModel(ref.provider, ref.model, undefined, cfg);
  
  const res = await completeSimple(model, {
    messages: [{
      role: "user",
      content: `Summarize the text to approximately ${targetLength} characters...`
    }]
  }, { apiKey, maxTokens: Math.ceil(targetLength / 2), temperature: 0.3 });
  
  return { summary: extractText(res), latencyMs: Date.now() - start };
}
```

**2. Truncation mode (when summarization is disabled)**: Simply truncate text to `maxLength - 3` characters and append `...`.

### Complete TTS Application Flow

`maybeApplyTtsToPayload` is the integration entry point between TTS and the messaging system, with the following flow:

```
Agent reply payload
  ↓ Check automatic mode (off/always/inbound/tagged)
  ↓ Parse [[tts:...]] directives → extract override parameters + clean text
  ↓ Skip condition checks (already has media attachments? text too short? contains MEDIA:?)
  ↓ Long text handling (summarize or truncate)
  ↓ textToSpeech() → try Provider chain (primary → fallback1 → fallback2)
  ↓ Save audio to temp file (auto-cleanup after 5 minutes)
  ↓ Return updated payload (mediaUrl = audio path, audioAsVoice = true/false)
```

### Provider Degradation Chain

`textToSpeech` tries all Providers in priority order. When the current Provider fails (missing API Key, timeout, error), it automatically tries the next one:

```typescript
const providers = resolveTtsProviderOrder(provider);  
// e.g., primary=openai → ["openai", "elevenlabs", "edge"]

for (const provider of providers) {
  try {
    // Try current Provider
    const audioBuffer = await callProvider(provider, text, config);
    writeFileSync(audioPath, audioBuffer);
    return { success: true, audioPath, provider };
  } catch (err) {
    lastError = `${provider}: ${err.message}`;
    // Continue to next
  }
}
return { success: false, error: lastError };
```

### Temporary File Management

Audio files generated by TTS are saved to the system temp directory (`/tmp/tts-xxx/`), with a timer registered via `scheduleCleanup` to auto-delete after 5 minutes:

```typescript
function scheduleCleanup(tempDir: string, delayMs = 5 * 60 * 1000): void {
  const timer = setTimeout(() => {
    rmSync(tempDir, { recursive: true, force: true });
  }, delayMs);
  timer.unref();  // don't prevent process exit
}
```

### System Prompt Injection

When TTS is enabled, `buildTtsSystemPromptHint` injects TTS-related hints into the Agent's system prompt:

```
Voice (TTS) is enabled.
Keep spoken text ≤1500 chars to avoid auto-summary (summary on).
Use [[tts:...]] and optional [[tts:text]]...[[/tts:text]] to control voice/expressiveness.
```

This lets the Agent know it's working in voice mode, generating text more suitable for reading aloud.

***

## Section Summary

1. **Three Provider Architecture**: OpenAI (high quality), ElevenLabs (voice cloning), Edge TTS (free fallback), auto-degrade by priority chain.
2. **Four Automatic Modes**: off/always/inbound/tagged, controlled by three-level priority: session > preference file > config.
3. **Channel Adaptation**: Telegram uses Opus format (voice bubble), other platforms use MP3 (file attachment), phone uses PCM raw audio.
4. **Agent Inline Directives**: Control Provider, voice, speech rate via `[[tts:...]]` tags, with administrator-configured override strategy determining which parameters can be overridden.
5. **Long Text Summarization**: Text exceeding limits is summarized by LLM or truncated before conversion to speech.
6. **Temporary File Management**: Audio files saved to `/tmp/`, auto-cleanup after 5 minutes, timer set with `unref()` to not prevent process exit.
