A text-to-speech app that reads text aloud and saves it as an MP3 — using pyttsx3 for offline local synthesis and gTTS for Google-quality audio.
pyttsx3 uses your OS text-to-speech engine — works offline, instant, free forever.
import pyttsx3
engine = pyttsx3.init()
# List available voices
voices = engine.getProperty('voices')
for i, v in enumerate(voices):
print(f"{i}: {v.name} ({v.languages})")
# Configure voice, speed, and volume
engine.setProperty('voice', voices[1].id) # 1 = female on most systems
engine.setProperty('rate', 150) # words per minute (default 200)
engine.setProperty('volume', 0.9) # 0.0 to 1.0
text = "Hello! This is Python speaking. You can convert any text to speech with just three lines of code."
engine.say(text)
engine.runAndWait()
print("Speech complete!")
gTTS uses Google Translate TTS — higher quality, but requires internet.
from gtts import gTTS
import pygame, os
def text_to_mp3(text, filename='speech.mp3', lang='en', slow=False):
tts = gTTS(text=text, lang=lang, slow=slow)
tts.save(filename)
print(f"Saved: {filename}")
return filename
def play_mp3(filename):
pygame.mixer.init()
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.quit()
text = "The quick brown fox jumps over the lazy dog."
text_to_mp3(text, 'fox.mp3')
play_mp3('fox.mp3')
Read a .txt file line by line so you can listen to articles, notes, or code.
import sys, pyttsx3
def read_file_aloud(filepath, rate=150):
engine = pyttsx3.init()
engine.setProperty('rate', rate)
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Split into chunks (pyttsx3 handles long text better in chunks)
paragraphs = [p.strip() for p in content.split('\n\n') if p.strip()]
print(f"Reading {len(paragraphs)} paragraphs from {filepath}")
for i, para in enumerate(paragraphs, 1):
print(f" Paragraph {i}/{len(paragraphs)}...")
engine.say(para)
engine.runAndWait()
print("Done!")
if len(sys.argv) > 1:
read_file_aloud(sys.argv[1])
else:
print("Usage: python tts.py myfile.txt")
print("\nDemo mode:")
engine = pyttsx3.init()
engine.say("Hello! Provide a filename as argument to read it aloud.")
engine.runAndWait()
Two TTS approaches in one tutorial — pyttsx3 for instant offline use, gTTS for broadcast-quality MP3s. Combine this with the PDF report generator or web scraper to build a podcast-from-articles tool that reads news to you while you commute.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.