Text-to-Speech Tool
This utility converts text into spoken audio using Google's Text-to-Speech API via the gTTS library. It supports saving to MP3, reading from text files, and optional immediate playback using the system's default media player.
Modules Used:
gTTS: To interface with Google Translate's text-to-speech API.- argparse: To handle command-line arguments.
os: To play the generated file (system dependent) and check file paths.
Installation
pip install gTTS
The Code
Save this as speak.py.
from gtts import gTTS
import argparse
import os
import sys
def text_to_speech(text, lang, output_file, play):
try:
print(f"Converting text to speech ({lang})...")
# slow=False reads at normal speed
tts = gTTS(text=text, lang=lang, slow=False)
tts.save(output_file)
print(f"Saved to {output_file}")
if play:
print("Playing audio...")
# Basic cross-platform playback attempt
if sys.platform == "win32":
os.startfile(output_file)
elif sys.platform == "darwin":
os.system(f"afplay {output_file}")
else:
# Linux
os.system(f"xdg-open {output_file}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CLI Text-to-Speech Tool")
parser.add_argument("input", help="Text to speak OR path to a text file")
parser.add_argument("-l", "--lang", default="en", help="Language code (default: en)")
parser.add_argument("-o", "--output", default="output.mp3", help="Output filename (default: output.mp3)")
parser.add_argument("-p", "--play", action="store_true", help="Play the audio after saving")
args = parser.parse_args()
# Check if input is a file path
text_data = args.input
if os.path.isfile(args.input):
try:
with open(args.input, 'r', encoding='utf-8') as f:
text_data = f.read()
print(f"Read {len(text_data)} characters from {args.input}")
except Exception as e:
print(f"Error reading file: {e}")
sys.exit(1)
text_to_speech(text_data, args.lang, args.output, args.play)
Usage
# Speak a simple phrase and play it
python speak.py "Hello, this is a test." --play
# Read from a file and save to Spanish audio
python speak.py story.txt --lang es --output story.mp3