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

# 语音转写与翻译

> 上传音频、读取文本，并区分转写与翻译。

语音转写和语音翻译均上传音频文件，返回文本，不返回合成语音。

| 需求 | 接口 | 结果 |
| - | - | - |
| 识别原语言内容 | [POST /v1/audio/transcriptions](/zh/api-reference/audio-transcriptions.md) | 原语言文本 |
| 翻译为英语 | [POST /v1/audio/translations](/zh/api-reference/audio-translations.md) | 英文文本 |

OpenAI 兼容翻译语义是“音频转英文”，不是任意目标语言翻译。若需要其他语言，可先转写，再把文本交给支持翻译的对话模型。转写模型不一定支持翻译端点。

## 上传录音

按 [Python SDK](/zh/guides/python.md)设置 `API_BASE_URL`（包含 `/v1`）、`API_KEY`、`API_MODEL`，另设置 `API_AUDIO_PATH` 为本地录音路径。保存为 `transcribe.py`，执行 `python transcribe.py transcribe`；选用支持翻译的模型后，执行 `python transcribe.py translate`。

运行时会上传录音。示例限制为非空且不超过 20 MiB；这是客户端示例限制，不是所有模型的统一上限。保留真实文件扩展名，并确认模型支持该编码。SDK 负责 multipart boundary，`file` 是文件字节，不是本地路径字符串或远程 URL。

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

mode = sys.argv[1] if len(sys.argv) == 2 else ""
if mode not in ("transcribe", "translate"):
    raise SystemExit("Usage: python transcribe.py transcribe|translate")
source = Path(os.environ["API_AUDIO_PATH"])
# A local example limit, not a universal provider upload limit.
if not 0 < source.stat().st_size <= 20 * 1024 * 1024:
    raise SystemExit("Choose a nonempty recording up to 20 MiB for this example.")

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:
        endpoint = client.audio.transcriptions if mode == "transcribe" else client.audio.translations
        with source.open("rb") as recording:
            result = endpoint.create(model=os.environ["API_MODEL"], file=recording, response_format="json")
        if not isinstance(result.text, str):
            raise ValueError("Expected a text field.")
        print(result.text)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed. Check the API address and network.")
    except ValueError:
        raise SystemExit("Invalid transcription response; expected JSON with text.")
```

## 返回格式与长录音

本例固定 `response_format: json`，读取 `text`；静音可能返回空文本，应由业务决定是否接受。`text`、`srt`、`vtt` 是文本响应，不能再按含 `text` 字段的 JSON 解析。需要时间戳时，确认模型支持 `verbose_json` 与 `timestamp_granularities[]`；时间戳或说话人分离不是所有模型都支持。

`language` 是转写输入语言提示，不是翻译目标；`prompt` 是上下文提示。长录音需按服务限制分段，保留时间偏移并处理重叠文字。不要假定上传限制只来自模型：反向代理、网关和渠道都可能更小。

本页使用已录制文件的非 SSE 响应。流式转写、说话人事件与实时音频协议需另外确认渠道支持，不可直接套用 Chat Completions 事件结构。

参考：[OpenAI 文件转写和翻译说明](https://developers.openai.com/api/docs/guides/speech-to-text)。

[Read in English](/en/guides/speech-to-text.md)

[相关指南：音频对话输入](/zh/guides/audio-input.md)


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