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 MP3 com o áudio de fala, mas você pode configurá-lo para retornar qualquer formato compatível.
Modelos de texto em fala
Para aplicações inteligentes em tempo real, use o modelo gpt-4o-mini-tts, nosso modelo de texto em fala mais recente e confiável. Você pode usar prompts para controlar aspectos da fala, incluindo:
Sotaque
Variedade de emoções
Entonação
Imitações
Velocidade da fala
Tom
Sussurros
Nossos outros modelos de texto em fala são tts-1 e tts-1-hd. O modelo tts-1 oferece menor latência, mas com qualidade inferior à do modelo tts-1-hd.
Opções de voz
O endpoint TTS oferece 13 vozes integradas para controlar como o texto é convertido em fala. Ouça e experimente essas vozes no OpenAI.fm, nossa demonstração interativa para testar o modelo de texto em fala mais recente 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.
A disponibilidade de vozes depende do modelo. Os modelos tts-1 e tts-1-hd oferecem suporte a um conjunto menor: alloy, ash, coral, echo, fable, onyx, nova, sage e shimmer.
Se você estiver usando a Realtime API, observe que o conjunto de vozes disponíveis é um pouco diferente. Consulte o guia de conversas em tempo real para ver as vozes disponíveis atualmente para uso em tempo real.
Streaming de áudio em tempo real
A Speech API oferece suporte a streaming de áudio em tempo real usando codificação de transferência em blocos. Isso significa que o áudio pode ser reproduzido antes que o arquivo completo seja gerado e disponibilizado.
Transmita áudio de fala por streaming a partir do texto de entrada diretamente para seus 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 os menores tempos de resposta, recomendamos usar wav ou pcm como formato de resposta.
Formatos de saída compatíveis
O formato de resposta padrão é mp3, mas outros formatos, como opus e wav, estão disponíveis.
MP3: O formato de resposta padrão para casos de uso em geral.
Opus: Para streaming e comunicação pela internet, com baixa latência.
AAC: Para compressão de áudio digital, preferido pelo YouTube, Android e iOS.
FLAC: Para compressão de áudio sem perdas, preferido por entusiastas de áudio para arquivamento.
WAV: Áudio WAV sem compressão, adequado para aplicações de baixa latência por evitar o processamento adicional de decodificação.
PCM: Semelhante ao WAV, mas contém as amostras brutas em 24 kHz (16 bits com sinal, low-endian), sem o cabeçalho.
Idiomas compatíveis
Em geral, o modelo TTS segue o modelo Whisper em relação ao suporte a idiomas. O Whisper oferece suporte aos seguintes idiomas e apresenta bom desempenho, apesar de as vozes serem otimizadas para o inglês:
Você pode gerar áudio de fala nesses idiomas fornecendo o texto de entrada no idioma de sua escolha.
Vozes personalizadas
Crie uma voz personalizada aprovada a partir da gravação de consentimento de um locutor e de uma amostra de
áudio correspondente. Consulte Vozes personalizadas para saber mais sobre elegibilidade,
requisitos de gravação, frases de consentimento e requisições à API.