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

# 语音合成

## 功能说明

对应工具标识 `text_to_speech`。

`text_to_speech` 将文本合成为语音，并把音频保存到本地。

导入路径：`from veadk.tools.builtin_tools.tts import text_to_speech`

## 环境变量与前提

<Warning>
  附加要求：

  1. 配置用于智能体推理模型的 API Key；
  2. 配置 VeSpeech 服务的 App ID 与 API Key。
</Warning>

环境变量：

* `MODEL_AGENT_API_KEY`：智能体推理模型的 API Key
* `TOOL_VESPEECH_APP_ID`：VeSpeech 服务的 App ID
* `TOOL_VESPEECH_API_KEY`：VeSpeech 服务的 API Key
* `TOOL_VESPEECH_SPEAKER`：音色，默认为 `zh_female_vv_uranus_bigtts`
* `TOOL_VESPEECH_AUDIO_OUTPUT_PATH`：音频输出目录，默认为系统临时目录

## 使用方法

```python title="examples/tools/tts/agent.py" lines theme={null}
import asyncio

from veadk import Agent, Runner
from veadk.memory.short_term_memory import ShortTermMemory
from veadk.tools.builtin_tools.tts import text_to_speech

agent = Agent(
    name="tts_agent",
    model_name="doubao-seed-2-1-pro-260628",
    description="An agent that speaks text aloud.",
    instruction="Use the text_to_speech tool to synthesize the user's text into speech.",
    tools=[text_to_speech],
)

runner = Runner(agent=agent, short_term_memory=ShortTermMemory())


async def main():
    response = await runner.run("把这句话读出来：你好，欢迎使用 VeADK")
    print(response)


if __name__ == "__main__":
    asyncio.run(main())
```

## 参数与输出格式

| 参数 | 类型 | 默认值 | 说明 |
| :- | :- | :- | :- |
| `text` | `str` | 必填 | 待合成文本 |
| `tool_context` | `ToolContext` | 自动注入 | 工具运行时上下文 |

成功结果为 `{"saved_audio_path": "..."}`，失败时可能返回 `error`。音频按 24 kHz PCM 保存为本地 `.pcm` 文件，不是可直接按 WAV 或 MP3 解码的文件；转码时需要匹配 PCM 音频参数。输出目录不存在时会创建，进程需具有写入权限

工具使用 `seed-tts-2.0` 资源和火山引擎语音服务地址，需为 App ID 开通该资源与音色。设置 `CLOUD_PROVIDER=byteplus` 不会自动切换语音端点。工具还可能尝试在运行机器播放音频，无可用音频设备时仍应检查输出文件

验证时先检查 `error`，再确认 `saved_audio_path` 指向存在且非空的文件；服务器上的本地路径不能直接作为终端用户可下载的链接，应由应用按需发布文件
