Python Text-to-Speech
Overview
The Audio API speech endpoint (TTS) can:
- Read blog posts aloud
- Generate multilingual audio
- Stream audio in real time
Important: You must disclose that listeners are hearing AI-generated speech, not a human voice.
Basic usage
Example
from pathlib import Path
from openai import OpenAI
client = OpenAI(
base_url="https://4zapi.com/v1",
api_key=key
)
speech_file_path = Path(__file__).parent / "speech.mp3"
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input="Today is a wonderful day to build something people love!"
)
response.stream_to_file(speech_file_path)
Features
Quality options
- tts-1: lower latency, good for realtime
- tts-1-hd: higher quality, may have less static
Voices
- alloy
- echo
- fable
- nova
- shimmer
- onyx
Output formats
| Format | Notes | Best for |
|---|---|---|
| MP3 | Default | General use |
| Opus | Low latency | Streaming / comms |
| AAC | Efficient | Mobile playback |
| FLAC | Lossless | Archiving |
| WAV | Uncompressed | Low-latency apps |
| PCM | Raw samples | 24kHz, 16-bit signed |
Streaming
from openai import OpenAI
client = OpenAI(
base_url="https://4zapi.com/v1",
api_key=key
)
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input="Hello world! This is a streaming test.",
)
response.stream_to_file("output.mp3")
Languages
Many languages, including:
- Asian: Chinese, Japanese, Korean, etc.
- European: English, French, German, etc.
- Others: Arabic, Hindi, etc.
Note: Current voices are optimized mainly for English
FAQ
Q: How do I control emotion?
A: There is no direct control. Capitalization or grammar may change the output, but results vary.
Q: Can I create a custom voice?
A: Custom voices are not supported.
Q: Who owns the audio?
A: The creator owns it, but you must tell users it is AI-generated.