Convert Text to Speech in Python
Text-to-Speech (TTS) makes human speech from written text. It helps you build accessible apps, automate voiceovers, or add audio feedback to systems. For example, if you need to add voice narration to a report or make an app easier for visually impaired users, TTS is what you need.
In the DataStride community, we often use Python for data science and AI. Python has strong, easy-to-use libraries for TTS, making it a good choice. Let's see how you can use TTS in Python with practical methods.
Understanding Text-to-Speech Libraries in Python
Python has several libraries for TTS. Popular ones include gTTS (Google Text-to-Speech) and pyttsx3. gTTS creates high-quality audio files using Google's online TTS service. pyttsx3 works offline and across different operating systems, so it's good for desktop apps.
This article will focus on gTTS because it's widely used, sounds natural, and is simple to integrate. It needs an internet connection because it sends text to Google's servers for processing and gets the audio back.
Installing gTTS
First, you need to install gTTS. Open your terminal or command prompt and run this command:
pip install gTTS
This command downloads and installs the gTTS library and its dependencies.
Your First Text-to-Speech Conversion with gTTS
Let's try a simple example: converting a short sentence into an audio file. This is a common task for new analysts who might need to create an audio alert or a basic voice message for a system.
from gtts import gTTS
import os
# The text you want to convert to speech
text_to_convert = "Hello DataStride learners! Welcome to the AI Frontiers blog."
# Choose a language (e.g., 'en' for English, 'hi' for Hindi)
language = 'en'
# Create a gTTS object
tts = gTTS(text=text_to_convert, lang=language, slow=False)
# Save the audio file
file_name = "datastride_intro.mp3"
tts.save(file_name)
print(f"Audio saved as {file_name}")
# Optional: Play the audio file (requires a media player installed on your system)
# os.system(f"start {file_name}") # For Windows
# os.system(f"afplay {file_name}") # For macOS
# os.system(f"mpg321 {file_name}") # For Linux (install mpg321 first)
In this code:
- You import
gTTSfrom thegttslibrary andosfor file operations. - You define
text_to_convertwith your message. - You specify the
language.gTTSsupports many languages; check its documentation for a list. Settingslow=Falsemakes the speech faster and more natural. - You create a
gTTSobject, giving it your text, language, and speed. - Finally,
tts.save(file_name)saves the speech as an MP3 file. You can play this file with any media player.
This script shows the main function. You can easily change it for different texts and languages.
Handling Dynamic Content and Data from Databases
In a real project, you might want to convert dynamic text, like data from a database, into speech. Imagine you have product names from an e-commerce database (ecm_products) and want to generate audio announcements for them. This is where your SQL and Python skills come together.
First, let's say you've fetched product names from the ecm_products table. For this example, we'll use a Python list to simulate this. In a real app, you'd use a database connector (like sqlite3, psycopg2, or mysql-connector-python) to query the database. For instance, you might run a SQL query like SELECT product_name FROM ecm_products WHERE category = 'Electronics' LIMIT 3;.
Let's assume you got this data:
product_names = [
"Smartphone X Pro",
"Wireless Earbuds Elite",
"Smartwatch Series 5"
]
Now, let's make an audio file for each product. You might use these in an automated inventory system or a product showcase.
from gtts import gTTS
import os
product_names = [
"Smartphone X Pro",
"Wireless Earbuds Elite",
"Smartwatch Series 5"
]
language = 'en'
output_dir = "product_audio"
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for i, product in enumerate(product_names):
text_to_convert = f"Introducing the new {product}. Discover its amazing features."
tts = gTTS(text=text_to_convert, lang=language, slow=False)
# Sanitize product name for filename
safe_product_name = product.replace(" ", "_").replace("'", "").replace("\"", "")
file_name = os.path.join(output_dir, f"product_{i+1}_{safe_product_name}.mp3")
tts.save(file_name)
print(f"Audio for '{product}' saved as {file_name}")
print(f"All product audio files saved in the '{output_dir}' directory.")
In this example:
- You define a list
product_names(like data fromecm_products). - You create an
output_dirto keep your audio files organized. - You loop through each product name.
- For each product, you build a descriptive
text_to_convertstring. - You generate and save the audio, making sure the filename is unique and clear. The
safe_product_namecreation is good practice to avoid problems with special characters in filenames.
This method is very flexible. You could fetch thousands of records from a database and make audio files for all of them. This is useful for automated customer service or e-learning platforms.
Common Pitfalls and How to Avoid Them
One common mistake with gTTS is forgetting it needs an internet connection. If your script runs without internet, or if there's a network problem, gTTS will raise an error (like requests.exceptions.ConnectionError).
How to spot it: Your script will fail with an error about network connectivity or a timeout. The audio file won't be made.
How to handle it:
- Ensure connectivity: Always check that your Python script's environment has a stable internet connection if you use
gTTS. - Implement error handling: Use
try-exceptblocks to handlerequests.exceptions.ConnectionErrororgtts.tts.gTTSError(thoughgTTSErroris less common for connection issues) gracefully.
Here's a quick example of error handling:
from gtts import gTTS
from gtts.tts import gTTSError
import requests # Needed for ConnectionError
text_to_convert = "This is a test message."
language = 'en'
file_name = "test_audio.mp3"
try:
tts = gTTS(text=text_to_convert, lang=language, slow=False)
tts.save(file_name)
print(f"Audio saved as {file_name}")
except requests.exceptions.ConnectionError:
print("Error: No internet connection. Please check your network.")
except gTTSError as e:
print(f"Error generating speech: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
This way, your program won't crash. You can tell the user about the error or log it. For offline TTS, think about pyttsx3, but know that its voice quality might not be as natural as gTTS.
Beyond Basic Conversion: Customisation
gTTS lets you customize a few things. You can change the language, as we saw, and adjust the slow parameter for speech speed. For more control over voice, pitch, and intonation, you might need to look at more powerful (and often paid, cloud-based) TTS APIs. These include Google Cloud Text-to-Speech, Amazon Polly, or Microsoft Azure Cognitive Services. These services usually offer more voices, emotions, and SSML (Speech Synthesis Markup Language) support for very precise control.
For most data tasks and simple apps, gTTS gives you a good mix of quality and ease of use. It's a great tool to have in your Python kit for adding sound to your data projects.
Key takeaways
- Text-to-Speech (TTS) turns written text into spoken audio. It's important for accessibility and automated voice features.
- Python's
gTTSlibrary is a popular choice for good-quality, natural-sounding speech. It uses Google's online service. - Install it easily with
pip install gTTS. - You can convert static or dynamic text (like from databases) into MP3 files with just a few lines of Python.
- Always handle
ConnectionErrorexceptions when usinggTTSbecause it needs an active internet connection.
Topic inspired by ListenData.
