媒体指南
音频与 Realtime
生成语音、转写音频、翻译语音或建立实时会话
结果是音频文件或文字时,使用音频端点;需要双向实时语音时,使用 Realtime WebSocket。
选择 API
| 需要什么 | API | 适合 |
|---|---|---|
| 文本转语音 | POST /v1/audio/speech | 需要从文本生成音频文件。 |
| 转写 | POST /v1/audio/transcriptions | 需要从音频文件得到文本。 |
| 音频翻译 | POST /v1/audio/translations | 需要从音频文件得到翻译后的文本。 |
| Realtime WebSocket | WS /v1/realtime?model={model} | 需要通过 WebSocket 传输双向流式音频或实时多模态事件。普通 GET /v1/realtime 只返回元信息。 |
选择模型
不要在客户端写死模型列表。打开 socket 前,请从模型详情确认是否支持 Realtime。
curl "https://api.tokenlab.sh/v1/models?recommended_for=tts" \
-H "Authorization: Bearer sk-your-api-key"
curl "https://api.tokenlab.sh/v1/models?recommended_for=stt" \
-H "Authorization: Bearer sk-your-api-key"音频请求
语音合成在 HTTP 响应中返回音频。转写和翻译可能返回最终文本,也可能返回已受理的任务。若响应包含任务 ID 和状态而非最终文本,请保存 ID,并按 poll_url 轮询至完成或失败。大文件应留足超时,并保留 请求 ID。
curl -X POST "https://api.tokenlab.sh/v1/audio/speech" \
-H "Authorization: Bearer sk-your-api-key" \
-H "Content-Type: application/json" \
-d '{
"model": "tts-1-hd",
"voice": "nova",
"input": "Welcome to TokenLab."
}' \
--output speech.mp3实时会话
打开 WebSocket 时,在查询参数中填写 model,在 Authorization 请求头中填写 API 密钥。事件格式以所选实时模型文档为准;会话结束时主动关闭 socket。
TokenLab 当前提供 Realtime WebSocket,不提供 OpenAI Realtime REST client secret、translation client secret、Calls 或旧版 beta session 管理 API。
运行下方服务器端示例前,安装 ws,将 TOKENLAB_REALTIME_MODEL 设置为当前模型详情明确声明 /v1/realtime 的模型。通过服务器环境提供 TOKENLAB_API_KEY;不能仅凭模型名称判断实时支持。
npm install wsimport WebSocket from 'ws';
const model = process.env.TOKENLAB_REALTIME_MODEL;
const apiKey = process.env.TOKENLAB_API_KEY;
if (!model || !apiKey) throw new Error('Set TOKENLAB_REALTIME_MODEL and TOKENLAB_API_KEY');
const url = new URL('wss://api.tokenlab.sh/v1/realtime');
url.searchParams.set('model', model);
const socket = new WebSocket(url, {
headers: { Authorization: `Bearer ${apiKey}` },
});
socket.on('message', (event) => console.log(event.toString()));
socket.on('error', (error) => console.error(error.message));
process.once('SIGINT', () => socket.close(1000, 'Client stopped'));在产品中展示状态
- 保存生成的音频文件,刷新页面时不要重复发起同一请求。
- 转写和翻译即使是同步调用,也应展示上传和处理中状态。
- 实时会话要处理关闭事件,只有用户重新开始会话时才重连。
- 不要把 API 密钥、私有 URL 或账户密钥放进音频文本输入。