OpenAI 文字转语音
tts-1、tts-1-hd和gpt-4o-mini-tts已弃用,将于 2027年1月6日关闭。应迁移到 Realtime API 的gpt-realtime-2.1-mini。这需要更换 API 工作流,不能把该模型直接用于/v1/audio/speech。关闭前,既有集成仍可使用下方 Speech API 流程。见弃用公告。
Audio API 的 speech 端点基于 GPT-4o mini TTS 文字转语音模型。原页导言称其包含 11 种内置声音,可用于:
- 朗读博客文章。
- 生成多种语言的语音。
- 通过流式传输实时输出音频。
以下是 alloy 声音示例:
alloy 声音示例:
使用政策要求向终端用户明确告知:听到的 TTS 声音由 AI 生成,并非真人。
快速开始
speech 端点接受三个关键输入:
从输入文字生成语音的请求示例:
来源示例 1(javascript):
程序文字译释132:今天是创造人们喜爱之物的美好一天!
程序文字译释133:用欢快、积极的语气讲话。
// [中文] 示例 1:快速开始;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
import fs from "fs";
import path from "path";
import OpenAI from "openai";
const openai = new OpenAI();
const speechFile = path.resolve("./speech.mp3");
const mp3 = await openai.audio.speech.create({
model: "gpt-4o-mini-tts",
voice: "coral",
input: "Today is a wonderful day to build something people love!",
instructions: "Speak in a cheerful and positive tone.",
});
const buffer = Buffer.from(await mp3.arrayBuffer());
await fs.promises.writeFile(speechFile, buffer);
来源示例 2(python):
沿用程序文字译释132。
沿用程序文字译释133。
## [中文] 示例 2:快速开始;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.speech.with_streaming_response.create;异步调用及事件接收顺序保留。
from pathlib import Path
from openai import OpenAI
client = OpenAI()
speech_file_path = Path(__file__).parent / "speech.mp3"
with client.audio.speech.with_streaming_response.create(
model="gpt-4o-mini-tts",
voice="coral",
input="Today is a wonderful day to build something people love!",
instructions="Speak in a cheerful and positive tone.",
) as response:
response.stream_to_file(speech_file_path)
来源示例 3(go):
沿用程序文字译释132。
沿用程序文字译释133。
// [中文] 示例 3:快速开始;以下保留本语言原始示例。
// [中文] 沿原示例执行这些方法:client.Audio.Speech.New;异步调用及事件接收顺序保留。
package main
import (
"context"
"io"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
response, err := client.Audio.Speech.New(context.Background(), openai.AudioSpeechNewParams{
Model: openai.SpeechModelGPT4oMiniTTS,
Voice: openai.AudioSpeechNewParamsVoiceUnion{OfAudioSpeechNewsVoiceString2: openai.String("coral")},
Input: "Today is a wonderful day to build something people love!",
Instructions: openai.String("Speak in a cheerful and positive tone."),
})
if err != nil {
panic(err)
}
defer response.Body.Close()
file, err := os.Create("speech.mp3")
if err != nil {
panic(err)
}
if _, err := io.Copy(file, response.Body); err != nil {
panic(err)
}
if err := file.Close(); err != nil {
panic(err)
}
}
来源示例 4(java):
沿用程序文字译释132。
沿用程序文字译释133。
// [中文] 示例 4:快速开始;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.audio.speech.SpeechCreateParams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
try (HttpResponse audio =
client
.audio()
.speech()
.create(
SpeechCreateParams.builder()
.model("gpt-4o-mini-tts")
.voice("coral")
.input("Today is a wonderful day to build something people love!")
.instructions("Speak in a cheerful and positive tone.")
.build())) {
Files.copy(audio.body(), Path.of("speech.mp3"), StandardCopyOption.REPLACE_EXISTING);
}
来源示例 5(csharp):
沿用程序文字译释132。
沿用程序文字译释133。
// [中文] 示例 5:快速开始;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.GenerateSpeechAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-4o-mini-tts";
AudioClient client = new(model, key);
BinaryData audio = await client.GenerateSpeechAsync(
"Today is a wonderful day to build something people love!",
GeneratedSpeechVoice.Coral,
new SpeechGenerationOptions
{
Instructions = "Speak in a cheerful and positive tone.",
}
);
await File.WriteAllBytesAsync("speech.mp3", audio.ToArray());
来源示例 6(ruby):
沿用程序文字译释132。
沿用程序文字译释133。
## [中文] 示例 6:快速开始;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.speech.create;异步调用及事件接收顺序保留。
require "openai"
client = OpenAI::Client.new
audio = client.audio.speech.create(
model: "gpt-4o-mini-tts",
voice: "coral",
input: "Today is a wonderful day to build something people love!",
instructions: "Speak in a cheerful and positive tone."
)
File.binwrite("speech.mp3", audio.read)
来源示例 7(bash):
程序文字译释134:待朗读文字:“今天是创造人们喜爱之物的美好一天!”表达指令:“用欢快、积极的语气讲话。”
## [中文] 示例 7:快速开始;以下保留本语言原始示例。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/speech;认证和请求体保持原示例形式。
curl https://api.openai.com/v1/audio/speech \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini-tts",
"input": "Today is a wonderful day to build something people love!",
"voice": "coral",
"instructions": "Speak in a cheerful and positive tone."
}' \
--output speech.mp3
来源示例 8(bash):
沿用程序文字译释132。
沿用程序文字译释133。
## [中文] 示例 8:快速开始;以下保留本语言原始示例。
## [中文] 通过 CLI 调用 Speech API,选择 coral 声音,将给定英文输入按欢快积极的语气生成到 speech.mp3。
## [中文] gpt-4o-mini-tts 是此旧集成示例的模型;按本页弃用说明安排迁移,不能只把模型名换成 Realtime 模型继续调用此命令。
openai audio:speech create \
--model gpt-4o-mini-tts \
--voice coral \
--instructions "Speak in a cheerful and positive tone." \
--input "Today is a wonderful day to build something people love!" \
--output speech.mp3
端点默认输出 MP3,也可以配置其他支持的格式。
文字转语音模型
已有 Speech API 集成中,gpt-4o-mini-tts 可通过提示词控制:
- 口音。
- 情绪范围。
- 语调。
- 模仿表现。
- 语速。
- 语气。
- 耳语。
另有 tts-1 与 tts-1-hd。tts-1 延迟较低,但质量低于 tts-1-hd。
声音选项
原页此处列出 13 种内置声音,控制文字如何呈现为语音。可在交互演示 OpenAI.fm 中试听,试用 OpenAI API 的文字转语音模型。声音目前针对英语优化。
alloy、ash、ballad、coral、echo、fable、nova、onyx、sage、shimmer、verse、marin、cedar。
为获得较好质量,推荐 marin 或 cedar。
可用声音取决于模型。tts-1、tts-1-hd 支持较小集合:alloy、ash、coral、echo、fable、onyx、nova、sage、shimmer。
译注:所提供原文的导言写 11 种,此处写 13 种并列出 13 个名称,数量不一致已列为待核项,不据此推定所有模型支持相同集合。
Realtime API 的声音集合略有不同,当前选项见 Realtime 对话指南。
实时流式音频
Speech API 支持分块传输编码,因此整个文件生成完并可获取之前,就能播放音频。
将输入文字生成的语音直接流式播放到扬声器:
来源示例 9(javascript):
沿用程序文字译释132。
沿用程序文字译释133。
// [中文] 示例 9:实时流式音频;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
import OpenAI from "openai";
import { playAudio } from "openai/helpers/audio";
const openai = new OpenAI();
const response = await openai.audio.speech.create({
model: "gpt-4o-mini-tts",
voice: "coral",
input: "Today is a wonderful day to build something people love!",
instructions: "Speak in a cheerful and positive tone.",
response_format: "wav",
});
await playAudio(response);
来源示例 10(python):
沿用程序文字译释132。
沿用程序文字译释133。
## [中文] 示例 10:实时流式音频;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
import asyncio
from openai import AsyncOpenAI
from openai.helpers import LocalAudioPlayer
openai = AsyncOpenAI()
async def main() -> None:
async with openai.audio.speech.with_streaming_response.create(
model="gpt-4o-mini-tts",
voice="coral",
input="Today is a wonderful day to build something people love!",
instructions="Speak in a cheerful and positive tone.",
response_format="pcm",
) as response:
await LocalAudioPlayer().play(response)
if __name__ == "__main__":
asyncio.run(main())
来源示例 11(go):
沿用程序文字译释132。
沿用程序文字译释133。
// [中文] 示例 11:实时流式音频;以下保留本语言原始示例。
// [中文] 沿原示例执行这些方法:client.Audio.Speech.New;异步调用及事件接收顺序保留。
package main
import (
"context"
"io"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
response, err := client.Audio.Speech.New(context.Background(), openai.AudioSpeechNewParams{
Model: openai.SpeechModelGPT4oMiniTTS,
Voice: openai.AudioSpeechNewParamsVoiceUnion{OfAudioSpeechNewsVoiceString2: openai.String("coral")},
Input: "Today is a wonderful day to build something people love!",
Instructions: openai.String("Speak in a cheerful and positive tone."),
ResponseFormat: openai.AudioSpeechNewParamsResponseFormatWAV,
})
if err != nil {
panic(err)
}
defer response.Body.Close()
if _, err := io.Copy(os.Stdout, response.Body); err != nil {
panic(err)
}
}
来源示例 12(java):
沿用程序文字译释132。
沿用程序文字译释133。
程序文字译释135:音频字节数。
// [中文] 示例 12:实时流式音频;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.audio.speech.SpeechCreateParams;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
try (HttpResponse audio =
client
.audio()
.speech()
.create(
SpeechCreateParams.builder()
.model("gpt-4o-mini-tts")
.voice("coral")
.input("Today is a wonderful day to build something people love!")
.instructions("Speak in a cheerful and positive tone.")
.responseFormat(SpeechCreateParams.ResponseFormat.PCM)
.streamFormat(SpeechCreateParams.StreamFormat.AUDIO)
.build())) {
AudioFormat format = new AudioFormat(24_000, 16, 1, true, false);
String outputPath = System.getenv("OPENAI_EXAMPLE_AUDIO_OUTPUT_PATH");
if (outputPath == null || outputPath.isBlank()) {
try (SourceDataLine speakers = AudioSystem.getSourceDataLine(format)) {
speakers.open(format);
speakers.start();
byte[] chunk = new byte[1024];
int bytesRead;
while ((bytesRead = audio.body().read(chunk)) != -1) {
speakers.write(chunk, 0, bytesRead);
}
speakers.drain();
}
} else {
try (OutputStream output = Files.newOutputStream(Path.of(outputPath))) {
long bytes = audio.body().transferTo(output);
System.out.println(bytes + " audio bytes");
}
}
}
来源示例 13(ruby):
程序文字译释136:欢迎使用OpenAI API。
## [中文] 示例 13:实时流式音频;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-mini-tts;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.speech.create;异步调用及事件接收顺序保留。
require "openai"
client = OpenAI::Client.new
audio = client.audio.speech.create(
model: "gpt-4o-mini-tts",
voice: "alloy",
input: "Welcome to the OpenAI API.",
response_format: :pcm,
stream_format: :audio
)
while (chunk = audio.read(1_024))
puts(chunk.bytesize)
end
来源示例 14(bash):
程序文字译释137:朗读“今天是创造人们喜爱之物的美好一天”,语气欢快积极,输出格式WAV。
## [中文] 示例 14:实时流式音频;以下保留本语言原始示例。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/speech;认证和请求体保持原示例形式。
curl https://api.openai.com/v1/audio/speech \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini-tts",
"input": "Today is a wonderful day to build something people love!",
"voice": "coral",
"instructions": "Speak in a cheerful and positive tone.",
"response_format": "wav"
}' | ffplay -i -
追求最快响应时间时,推荐 wav 或 pcm 响应格式。
支持的输出格式
默认是 mp3,也支持 opus、wav 等格式:
- MP3:默认格式,适用于一般场景。
- Opus:低延迟,适合网络流传输与通信。
- AAC:数字音频压缩,常用于 YouTube、Android、iOS。
- FLAC:无损压缩,适合音频爱好者归档。
- WAV:未压缩,避免解码开销,适合低延迟应用。
- PCM:类似 WAV,但不带文件头,为 24 kHz、16 位有符号、小端序的原始采样。
支持的语言
TTS 的语言支持大体沿用 Whisper。尽管声音针对英语优化,Whisper 支持的以下语言也可获得良好表现:
南非荷兰语、阿拉伯语、亚美尼亚语、阿塞拜疆语、白俄罗斯语、波斯尼亚语、保加利亚语、加泰罗尼亚语、中文、克罗地亚语、捷克语、丹麦语、荷兰语、英语、爱沙尼亚语、芬兰语、法语、加利西亚语、德语、希腊语、希伯来语、印地语、匈牙利语、冰岛语、印度尼西亚语、意大利语、日语、卡纳达语、哈萨克语、韩语、拉脱维亚语、立陶宛语、马其顿语、马来语、马拉地语、毛利语、尼泊尔语、挪威语、波斯语、波兰语、葡萄牙语、罗马尼亚语、俄语、塞尔维亚语、斯洛伐克语、斯洛文尼亚语、西班牙语、斯瓦希里语、瑞典语、他加禄语、泰米尔语、泰语、土耳其语、乌克兰语、乌尔都语、越南语和威尔士语。
用所选语言提供输入文字,即可生成该语言的语音。
自定义声音
使用讲话者的授权录音及匹配样本,创建获准使用的自定义声音。资格、录音要求、授权声明与请求见自定义声音。
创建声音
按照创建自定义声音操作。
生成语音时使用声音
生成语音时传入已创建的声音 ID。见语音生成示例。
相关指南
- Realtime 与音频概览:为语音智能体、翻译、转录和语音生成选择合适路径。
- 音频与语音概念:了解音频模态、语音任务、流式处理和按请求调用的 API。

TRAE-AI编程


更多建议: