Genera audio hablado a partir del texto de entrada
Python
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
De forma predeterminada, el punto de acceso genera un MP3 del audio hablado, pero puedes configurarlo para que genere cualquier formato compatible.
Modelos de texto a voz
Para aplicaciones inteligentes en tiempo real, usa el modelo gpt-4o-mini-tts, nuestro modelo de texto a voz más reciente y confiable. Puedes darle instrucciones mediante prompts para controlar aspectos del habla, como:
Acento
Rango emocional
Entonación
Imitaciones
Velocidad del habla
Tono
Susurros
Nuestros otros modelos de texto a voz son tts-1 y tts-1-hd. El modelo tts-1 ofrece una latencia menor, pero con una calidad inferior a la del modelo tts-1-hd.
Opciones de voz
El punto de acceso TTS ofrece 13 voces integradas para controlar cómo se genera la voz a partir del texto. Escucha y experimenta con estas voces en OpenAI.fm, nuestra demostración interactiva para probar el modelo de texto a voz más reciente de la API de OpenAI. Actualmente, las voces están optimizadas para el inglés.
alloy
ash
ballad
coral
echo
fable
nova
onyx
sage
shimmer
verse
marin
cedar
Para obtener la mejor calidad, recomendamos usar marin o cedar.
La disponibilidad de voces depende del modelo. Los modelos tts-1 y tts-1-hd admiten un conjunto más reducido: alloy, ash, coral, echo, fable, onyx, nova, sage y shimmer.
Si usas la Realtime API, ten en cuenta que el conjunto de voces disponibles es ligeramente diferente. Consulta la guía de conversaciones en tiempo real para conocer las voces disponibles actualmente para uso en tiempo real.
Streaming de audio en tiempo real
La API de voz admite streaming de audio en tiempo real mediante codificación de transferencia por bloques. Esto significa que el audio puede reproducirse antes de que se genere el archivo completo y esté disponible.
Transmite audio hablado a partir del texto de entrada directamente a tus altavoces
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 obtener los tiempos de respuesta más rápidos, recomendamos usar wav o pcm como formato de respuesta.
Formatos de salida compatibles
El formato de respuesta predeterminado es mp3, pero también hay otros formatos disponibles, como opus y wav.
MP3: el formato de respuesta predeterminado para casos de uso generales.
Opus: para streaming y comunicación por internet, con baja latencia.
AAC: para compresión de audio digital, el formato preferido de YouTube, Android e iOS.
FLAC: para compresión de audio sin pérdida, el formato preferido de los aficionados al audio para archivar grabaciones.
WAV: audio WAV sin comprimir, adecuado para aplicaciones de baja latencia, ya que evita el procesamiento adicional de la decodificación.
PCM: similar a WAV, pero contiene las muestras sin procesar a 24 kHz (16 bits con signo, low-endian), sin encabezado.
Idiomas compatibles
En general, el modelo TTS admite los mismos idiomas que el modelo Whisper. Whisper admite los siguientes idiomas y ofrece buenos resultados, aunque las voces están optimizadas para el inglés:
Puedes generar audio hablado en estos idiomas proporcionando texto de entrada en el idioma que elijas.
Voces personalizadas
Crea una voz personalizada aprobada a partir de una grabación del consentimiento de un hablante y una muestra de
audio correspondiente. Consulta Voces personalizadas para conocer los criterios de elegibilidad,
los requisitos de grabación, las frases de consentimiento y las solicitudes a la API.