The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Convert text to speech with Python

Converting text to speech (TTS) in Python can be easily achieved using several libraries. One of the most popular and straightforward libraries is gTTS (Google Text-to-Speech). Another widely used option is pyttsx3, which works offline and supports multiple TTS engines.

Below is a detailed guide on how to convert text to speech in Python using these libraries:


Using gTTS (Google Text-to-Speech)

gTTS is a Python library and CLI tool to interface with Google Translate’s text-to-speech API. It requires an internet connection.

Installation:

bash
pip install gtts

Example code:

python
from gtts import gTTS import os text = "Hello, this is a sample text to speech conversion using gTTS in Python." # Create gTTS object tts = gTTS(text=text, lang='en', slow=False) # Save the audio file tts.save("output.mp3") # Play the audio (for Windows) os.system("start output.mp3") # For macOS use: os.system("afplay output.mp3") # For Linux use: os.system("mpg321 output.mp3") or "mpv output.mp3"

Using pyttsx3 (Offline Text-to-Speech)

pyttsx3 works offline and uses the speech engines already installed on your system (SAPI5 on Windows, NSSpeechSynthesizer on macOS, espeak on Linux).

Installation:

bash
pip install pyttsx3

Example code:

python
import pyttsx3 engine = pyttsx3.init() text = "Hello, this is a sample text to speech conversion using pyttsx3 in Python." # Set properties (optional) engine.setProperty('rate', 150) # Speed (words per minute) engine.setProperty('volume', 1.0) # Volume (0.0 to 1.0) # Convert text to speech engine.say(text) # Blocks while processing all the currently queued commands engine.runAndWait()

Additional Features & Customization

  • Changing voice (male/female):

python
voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) # Change index to 0 or 1 for male/female depending on system
  • Saving speech to file (using pyttsx3):

python
engine.save_to_file(text, 'output.wav') engine.runAndWait()

Summary

  • Use gTTS for quick, easy, and natural-sounding speech with internet access.

  • Use pyttsx3 for offline usage with control over voice properties and engine options.

This approach enables you to integrate text-to-speech functionality smoothly into your Python applications or scripts.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About