OpenAI TTS
Text-to-speech conversion using OpenAI's TTS API for generating high-quality, natural-sounding audio from text.
Features
- 6 different voice options (male/female)
- Standard and HD quality models
- Automatic text chunking for long content (4096 char limit)
- Multiple output formats (mp3, opus, aac, flac)
Activation
This skill activates when the user:
- Requests audio/voice output: "read this to me", "convert to audio", "generate speech", "make this an audio file"
- Uses keywords: "tts", "openai tts", "text to speech", "voice", "audio", "podcast"
- Needs content spoken for accessibility, multitasking, or podcast creation
- Specifies voice preferences: "alloy", "echo", "fable", "onyx", "nova", "shimmer"
- Asks to "narrate", "speak", or "vocalize" text
Requirements
OPENAI_API_KEY environment variable must be set
- Python 3.8+
- Dependencies:
openai, pydub (optional, for long text)
Voices
| Voice |
Type |
Description |
| alloy |
Neutral |
Balanced, versatile |
| echo |
Male |
Warm, conversational |
| fable |
Neutral |
Expressive, storytelling |
| onyx |
Male |
Deep, authoritative |
| nova |
Female |
Friendly, upbeat |
| shimmer |
Female |
Clear, professional |
Usage
Basic Usage
from openai import OpenAI
import os
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
response = client.audio.speech.create(
model="tts-1", # or "tts-1-hd" for higher quality
voice="onyx", # choose from: alloy, echo, fable, onyx, nova, shimmer
input="Your text here",
speed=1.0 # 0.25 to 4.0 (optional)
)
with open("output.mp3", "wb") as f:
for chunk in response.iter_bytes():
f.write(chunk)
Command Line
# Basic
python -c "
from openai import OpenAI
client = OpenAI()
response = client.audio.speech.create(model='tts-1', voice='onyx', input='Hello world')
open('output.mp3', 'wb').write(response.content)
"
Long Text (Auto-chunking)
from openai import OpenAI
from pydub import AudioSegment
import tempfile
import os
import re
client = OpenAI()
MAX_CHARS = 4096
def split_text(text):
if len(text) <= MAX_CHARS:
return [text]
chunks = []
sentences = re.split(r'(?<=[.!?])\s+', text)
current = ''
for sentence in sentences:
if len(current) + len(sentence) + 1 <= MAX_CHARS:
current += (' ' if current else '') + sentence
else:
if current:
chunks.append(current)
current = sentence
if current:
chunks.append(current)
return chunks
def generate_tts(text, output_path, voice='onyx', model='tts-1'):
chunks = split_text(text)
if len(chunks) == 1:
response = client.audio.speech.create(model=model, voice=voice, input=text)
with open(output_path, 'wb') as f:
f.write(response.content)
else:
segments = []
for chunk in chunks:
response = client.audio.speech.create(model=model, voice=voice, input=chunk)
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp:
tmp.write(response.content)
segments.append(AudioSegment.from_mp3(tmp.name))
os.unlink(tmp.name)
combined = segments[0]
for seg in segments[1:]:
combined += seg
combined.export(output_path, format='mp3')
return output_path
# Usage
generate_tts("Your long text here...", "output.mp3", voice="nova")
Models
| Model |
Quality |
Speed |
Cost |
| tts-1 |
Standard |
Fast |
$0.015/1K chars |
| tts-1-hd |
High Definition |
Slower |
$0.030/1K chars |
Output Formats
Supported formats: mp3 (default), opus, aac, flac
response = client.audio.speech.create(
model="tts-1",
voice="onyx",
input="Hello",
response_format="opus" # or mp3, aac, flac
)
Error Handling
from openai import OpenAI, APIError, RateLimitError
import time
client = OpenAI()
def generate_with_retry(text, voice='onyx', max_retries=3):
for attempt in range(max_retries):
try:
response = client.audio.speech.create(
model="tts-1",
voice=voice,
input=text
)
return response.content
except RateLimitError:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise
except APIError as e:
print(f"API Error: {e}")
raise
return None
Examples
Convert Article to Podcast
def article_to_podcast(article_text, output_file):
intro = "Welcome to today's article reading."
outro = "Thank you for listening."
full_text = f"{intro}\n\n{article_text}\n\n{outro}"
generate_tts(full_text, output_file, voice='nova', model='tts-1-hd')
print(f"Podcast saved to {output_file}")
Batch Processing
def batch_tts(texts, output_dir, voice='onyx'):
import os
os.makedirs(output_dir, exist_ok=True)
for i, text in enumerate(texts):
output_path = os.path.join(output_dir, f"audio_{i+1}.mp3")
generate_tts(text, output_path, voice=voice)
print(f"Generated: {output_path}")
Links
1---2name: openai-tts-23description: Text-to-speech conversion using OpenAI's TTS API for generating high-quality, natural-sounding audio. Supports 6 voices (alloy, echo, fable, onyx, nova, shimmer), speed control (0.25x-4.0x), HD quality model, multiple output formats (mp3, opus, aac, flac), and automatic text chunking for long content (4096 char limit per request). Use when: (1) User requests audio/voice output with triggers like "read this to me", "convert to audio", "generate speech", "text to speech", "tts", "narrate", "speak", or when keywords "openai tts", "voice", "podcast" appear. (2) Content needs to be spoken rather than read (multitasking, accessibility). (3) User wants specific voice preferences like "alloy", "echo", "fable", "onyx", "nova", "shimmer" or speed adjustments.4---5
6# OpenAI TTS
7
8Text-to-speech conversion using OpenAI's TTS API for generating high-quality, natural-sounding audio from text.
9
10## Features
11- 6 different voice options (male/female)
12- Standard and HD quality models
13- Automatic text chunking for long content (4096 char limit)
14- Multiple output formats (mp3, opus, aac, flac)
15
16## Activation
17
18This skill activates when the user:
19- Requests audio/voice output: "read this to me", "convert to audio", "generate speech", "make this an audio file"
20- Uses keywords: "tts", "openai tts", "text to speech", "voice", "audio", "podcast"
21- Needs content spoken for accessibility, multitasking, or podcast creation
22- Specifies voice preferences: "alloy", "echo", "fable", "onyx", "nova", "shimmer"
23- Asks to "narrate", "speak", or "vocalize" text
24
25## Requirements
26
27- `OPENAI_API_KEY` environment variable must be set
28- Python 3.8+
29- Dependencies: `openai`, `pydub` (optional, for long text)
30
31## Voices
32
33| Voice | Type | Description |
34|-------|------|-------------|
35| alloy | Neutral | Balanced, versatile |
36| echo | Male | Warm, conversational |
37| fable | Neutral | Expressive, storytelling |
38| onyx | Male | Deep, authoritative |
39| nova | Female | Friendly, upbeat |
40| shimmer | Female | Clear, professional |
41
42## Usage
43
44### Basic Usage
45```python
46from openai import OpenAI
47import os
48
49client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
50
51response = client.audio.speech.create(
52 model="tts-1", # or "tts-1-hd" for higher quality
53 voice="onyx", # choose from: alloy, echo, fable, onyx, nova, shimmer
54 input="Your text here",
55 speed=1.0 # 0.25 to 4.0 (optional)
56)
57
58with open("output.mp3", "wb") as f:
59 for chunk in response.iter_bytes():
60 f.write(chunk)
61```
62
63### Command Line
64```bash
65# Basic
66python -c "
67from openai import OpenAI
68client = OpenAI()
69response = client.audio.speech.create(model='tts-1', voice='onyx', input='Hello world')
70open('output.mp3', 'wb').write(response.content)
71"
72```
73
74### Long Text (Auto-chunking)
75```python
76from openai import OpenAI
77from pydub import AudioSegment
78import tempfile
79import os
80import re
81
82client = OpenAI()
83MAX_CHARS = 4096
84
85def split_text(text):
86 if len(text) <= MAX_CHARS:
87 return [text]
88
89 chunks = []
90 sentences = re.split(r'(?<=[.!?])\s+', text)
91 current = ''
92
93 for sentence in sentences:
94 if len(current) + len(sentence) + 1 <= MAX_CHARS:
95 current += (' ' if current else '') + sentence
96 else:
97 if current:
98 chunks.append(current)
99 current = sentence
100
101 if current:
102 chunks.append(current)
103
104 return chunks
105
106def generate_tts(text, output_path, voice='onyx', model='tts-1'):
107 chunks = split_text(text)
108
109 if len(chunks) == 1:
110 response = client.audio.speech.create(model=model, voice=voice, input=text)
111 with open(output_path, 'wb') as f:
112 f.write(response.content)
113 else:
114 segments = []
115 for chunk in chunks:
116 response = client.audio.speech.create(model=model, voice=voice, input=chunk)
117 with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp:
118 tmp.write(response.content)
119 segments.append(AudioSegment.from_mp3(tmp.name))
120 os.unlink(tmp.name)
121
122 combined = segments[0]
123 for seg in segments[1:]:
124 combined += seg
125 combined.export(output_path, format='mp3')
126
127 return output_path
128
129# Usage
130generate_tts("Your long text here...", "output.mp3", voice="nova")
131```
132
133## Models
134
135| Model | Quality | Speed | Cost |
136|-------|---------|-------|------|
137| tts-1 | Standard | Fast | $0.015/1K chars |
138| tts-1-hd | High Definition | Slower | $0.030/1K chars |
139
140## Output Formats
141
142Supported formats: `mp3` (default), `opus`, `aac`, `flac`
143
144```python
145response = client.audio.speech.create(
146 model="tts-1",
147 voice="onyx",
148 input="Hello",
149 response_format="opus" # or mp3, aac, flac
150)
151```
152
153## Error Handling
154
155```python
156from openai import OpenAI, APIError, RateLimitError
157import time
158
159client = OpenAI()
160
161def generate_with_retry(text, voice='onyx', max_retries=3):
162 for attempt in range(max_retries):
163 try:
164 response = client.audio.speech.create(
165 model="tts-1",
166 voice=voice,
167 input=text
168 )
169 return response.content
170 except RateLimitError:
171 if attempt < max_retries - 1:
172 time.sleep(2 ** attempt) # Exponential backoff
173 continue
174 raise
175 except APIError as e:
176 print(f"API Error: {e}")
177 raise
178
179 return None
180```
181
182## Examples
183
184### Convert Article to Podcast
185```python
186def article_to_podcast(article_text, output_file):
187 intro = "Welcome to today's article reading."
188 outro = "Thank you for listening."
189
190 full_text = f"{intro}\n\n{article_text}\n\n{outro}"
191
192 generate_tts(full_text, output_file, voice='nova', model='tts-1-hd')
193 print(f"Podcast saved to {output_file}")
194```
195
196### Batch Processing
197```python
198def batch_tts(texts, output_dir, voice='onyx'):
199 import os
200 os.makedirs(output_dir, exist_ok=True)
201
202 for i, text in enumerate(texts):
203 output_path = os.path.join(output_dir, f"audio_{i+1}.mp3")
204 generate_tts(text, output_path, voice=voice)
205 print(f"Generated: {output_path}")
206```
207
208## Links
209
210- [OpenAI TTS Documentation](https://platform.openai.com/docs/guides/text-to-speech)
211- [OpenAI API Reference](https://platform.openai.com/docs/api-reference/audio/createSpeech)
212- [Pricing](https://openai.com/pricing)