Prompt
How do I generate MP3 speech from text in Python?
Latest observation
Oct 11, 2026
OpenAI APIWeb search: off
To generate MP3 speech from text in Python, the simplest options are:
1) Use Google Text-to-Speech (gTTS) — easy and free for basic use
Install
pip install gTTS
Example
from gtts import gTTS
text = "Hello, this is a text to speech example in Python."
tts = gTTS(text=text, lang="en")
tts.save("speech.mp3")
print("Saved speech.mp3")
Notes
- Produces an MP3 file directly.
- Requires internet access.
- Good for small projects or prototypes.
2) Use pyttsx3 — offline, but outputs WAV more naturally
pyttsx3 works offline, but it usually saves to WAV or plays audio rather than creating MP3 directly. If you need MP3, you’d typically convert the WAV to MP3 afterward.
Install
pip install pyttsx3 pydub
You’ll also need ffmpeg installed for conversion.
Example
import pyttsx3
from pydub import AudioSegment
text = "Hello, this is offline speech generation."
engine = pyttsx3.init()
engine.save_to_file(text, "speech.wav")
engine.runAndWait()
audio = AudioSegment.from_wav("speech.wav")
audio.export("speech.mp3", format="mp3")
print("Saved speech.mp3")
3) Use cloud TTS services for higher quality voices
If you want more natural voices and control, use:
- Google Cloud Text-to-Speech
- Amazon Polly
- Microsoft Azure Speech
These typically require an API key and billing setup, but they can generate MP3 directly.
Recommended approach
- Quick and easy:
gTTS - Offline:
pyttsx3+ffmpeg - Best quality: cloud TTS APIs
If you want, I can show you:
- a version that reads text from a file,
- a Flask/FastAPI endpoint that returns MP3, or
- a script using AWS/Google/Azure TTS.