Aprenda a transformar texto em fala com sonoridade natural.
Os modelos tts-1, tts-1-hd e gpt-4o-mini-tts estão obsoletos e serão
desativados em 6 de janeiro de 2027. Migre para gpt-realtime-2.1-mini usando a
Realtime API. A migração exige mudar a forma de chamar a API,
pois gpt-realtime-2.1-mini não é compatível com /v1/audio/speech.
Até a desativação dos modelos, as integrações existentes podem usar os fluxos da API de fala
descritos abaixo. Consulte o aviso de descontinuação.
Nossas políticas de uso exigem que você
informe claramente aos usuários finais que a voz que estão ouvindo é sintetizada por IA
e não é uma voz humana.
Início rápido
O endpoint speech recebe três parâmetros principais:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import 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);
1
2
3
4
5
6
7
8
9
10
11
12
13from pathlib import Pathfrom openai import OpenAIclient = 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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34package mainimport ( "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) }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import 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);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17using OpenAI.Audio;#pragma warning disable OPENAI001string 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());
1
2
3
4
5
6
7
8
9
10require "openai"client = OpenAI::Client.newaudio = 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)
1
2
3
4
5
6
7
8
9
10curl 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
1
2
3
4
5
6openai 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
Por padrão, o endpoint retorna um arquivo MP3 com a fala gerada. Você pode configurá-lo para retornar o áudio em qualquer formato compatível.
Modelos de conversão de texto em fala
Nas integrações existentes com a API de fala, o modelo gpt-4o-mini-tts permite usar prompts para controlar os seguintes aspectos da fala:
Sotaque
Variedade de emoções expressas
Entonação
Imitação de vozes
Velocidade da fala
Tom de voz
Sussurros
Nossos outros modelos de conversão de texto em fala são tts-1 e tts-1-hd. O modelo tts-1 oferece menor latência, mas a qualidade do áudio é inferior à do modelo tts-1-hd.
Opções de voz
O endpoint de conversão de texto em fala oferece 13 vozes predefinidas para você escolher como o texto será lido. Ouça e experimente essas vozes no OpenAI.fm, nossa demonstração interativa do modelo mais recente de conversão de texto em fala da API da OpenAI. Atualmente, as vozes são otimizadas para o inglês.
alloy
ash
ballad
coral
echo
fable
nova
onyx
sage
shimmer
verse
marin
cedar
Para obter a melhor qualidade, recomendamos usar marin ou cedar.
As vozes disponíveis variam conforme o modelo. Os modelos tts-1 e tts-1-hd oferecem menos opções: alloy, ash, coral, echo, fable, onyx, nova, sage e shimmer.
A API de fala permite transmitir áudio em tempo real por streaming usando codificação de transferência em blocos. Assim, você pode começar a reproduzir o áudio antes que o arquivo completo seja gerado e disponibilizado.
Transmita a fala gerada a partir do texto diretamente para os alto-falantes
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14import 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);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import asynciofrom openai import AsyncOpenAIfrom openai.helpers import LocalAudioPlayeropenai = AsyncOpenAI()asyncdefmain() -> None:asyncwith 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())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27package mainimport ( "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) }}
1
2
3
4
5
6
7
8
9
10curl 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 -
Para obter respostas mais rápidas, recomendamos usar wav ou pcm como formato de resposta.
Formatos de saída compatíveis
O formato de resposta padrão é mp3, mas há outros formatos disponíveis, como opus e wav.
MP3: formato de resposta padrão para uso geral.
Opus: oferece baixa latência para streaming e comunicação pela internet.
AAC: formato de compressão de áudio digital preferido pelo YouTube, pelo Android e pelo iOS.
FLAC: formato de compressão de áudio sem perdas, muito usado por entusiastas de áudio para arquivar gravações.
WAV: áudio WAV sem compressão, indicado para aplicativos de baixa latência porque evita o custo de decodificação.
PCM: semelhante ao WAV, mas contém apenas as amostras brutas a 24 kHz (16 bits com sinal, em ordem little-endian), sem cabeçalho.
Idiomas compatíveis
De modo geral, o modelo de conversão de texto em fala é compatível com os mesmos idiomas que o modelo Whisper. O Whisper oferece suporte aos idiomas a seguir e apresenta bom desempenho, embora as vozes sejam otimizadas para o inglês:
Para gerar fala em um desses idiomas, forneça o texto de entrada no idioma desejado.
Vozes personalizadas
Para criar uma voz personalizada aprovada, use uma gravação de consentimento e uma amostra de áudio da mesma pessoa. Consulte Vozes personalizadas para saber quem pode usar o recurso, quais são os requisitos de gravação, quais frases usar para registrar o consentimento e como fazer as requisições à API.