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

# 语音合成

> 将文本转换为音频，并正确保存二进制响应。

[语音合成接口](/zh/api-reference/audio-speech)将文本转换为音频。先确认 `API_MODEL` 支持语音合成，并设置该模型可用的 `API_VOICE`；对话模型和音色名称不能任意混用。

## 保存 MP3

按 [Python SDK](/zh/guides/python)配置 `API_BASE_URL`（包含 `/v1`）、`API_KEY`、`API_MODEL`，另设置 `API_VOICE`。保存为 `speech.py` 并执行 `python speech.py`，结果写入当前目录的 `speech.mp3`；已有文件不会覆盖。

示例请求 `response_format: mp3`，按音频字节读取，限制输出为 16 MiB（仅示例限制）。它检查状态和 Content-Type，拒绝把 JSON 错误当作音频；不进行完整音频解码校验。

```python theme={null}
import os
from pathlib import Path
from openai import OpenAI, APIConnectionError, APIStatusError

with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=120.0, max_retries=0) as client:
    try:
        with client.audio.speech.with_streaming_response.create(
            model=os.environ["API_MODEL"], voice=os.environ["API_VOICE"],
            input="Welcome to our application.", response_format="mp3",
        ) as response:
            media_type = response.headers.get("content-type", "").split(";")[0].lower()
            if not (media_type.startswith("audio/") or media_type == "application/octet-stream"):
                raise ValueError("Expected audio bytes.")
            audio = bytearray()
            for chunk in response.iter_bytes():
                audio.extend(chunk)
                if len(audio) > 16 * 1024 * 1024:
                    raise ValueError("Example output exceeds 16 MiB.")
            if not audio:
                raise ValueError("Empty audio.")
            with Path("speech.mp3").open("xb") as target:
                target.write(audio)
            print("Saved speech.mp3")
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed; check before resubmitting speech.")
    except (ValueError, OSError):
        raise SystemExit("Cannot save speech. Check the content type, size, and output file.")
```

## 格式和流式边界

`input` 是文本，`voice` 是音色，`instructions` 是部分模型支持的风格指令。`speed`、输入长度、语言和输出编码均受具体模型限制；更换文件扩展名不会转换编码。PCM 还需要正确的采样率、位深和声道信息，不能直接当作 WAV。

SDK 的 `with_streaming_response` 表示分块读取 HTTP 音频字节，不等于 SSE，也不是双向实时语音会话。只有渠道明确支持时才使用 `stream_format: sse`，并使用对应事件解析器。交互式麦克风、WebRTC 和 Realtime 会话不属于此文件合成流程。

## 失败处理

非 2xx 时检查模型、音色、参数、权限和日志。音频传输中断后不能把部分文件当完整结果；本例完整收取后才写文件。客户端关闭自动重试，避免不明确的失败引起重复合成。产品中应清楚标示 AI 合成语音；OpenAI 上游对此有明确要求，见[语音合成说明](https://developers.openai.com/api/docs/guides/text-to-speech)。

[Read in English](/en/guides/speech)


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