How to Convert Text to Voice Using Python

Well, I recently explored something super cool converting text to speech using Python, and believe me, it’s way simpler than I expected. In this post, I’ll walk you through the exact steps I followed using the pyttsx3 library.

What is Pyttsx3

pyttsx3 is a text to speech conversion library in Python. Unlike some libraries that require an internet connection, pyttsx3 works offline and supports multiple voices and languages, depending on your system.

Installation

First, I had to install the library:

pip install pyttsx3

Code Explanation

Here’s the simplest program to make Python speak:

import pyttsx3
# pip install pyttsx3

This line imports the pyttsx3 library.

bot = pyttsx3.init()

This initializes the text-to-speech engine and assigns it to a variable called bot. Think of it as your own speaking assistant.

bot.say("Hello World")

This tells the engine what to say. It doesn’t speak just yet it queues the text.

bot.runAndWait()

This is the magic button. It processes and speaks the queued text.

Output:

When you run the above code, you’ll literally hear a voice say: “Hello World” from your speakers.

Now Let’s Add More Functionalities to Practice

Once I got the basics, I started experimenting. Here’s what I tried next:

Convert User Input Text to Speech

I wanted to input custom text, so I wrote:

import pyttsx3

bot = pyttsx3.init()

text = input("Enter the text you want to convert to speech: ")
bot.say(text)
bot.runAndWait()

Now Python reads out whatever I type in!

Change the Voice

I found out that I could change the voice between male and female (depending on the system):

 = bot.getProperty('voices')
bot.setProperty('voice', voices[1].id) # Try 0 or 1

bot.say("This is a female voice.")
bot.runAndWait()

Adjust Speaking Speed

Too fast? Too slow? No worries, here’s how I adjusted the speaking rate:

rate = bot.getProperty('rate')
print(f"Current rate: {rate}")
bot.setProperty('rate', 150) # Default is around 200

bot.say("This is spoken at a slower speed.")
bot.runAndWait()

Adjust Volume

I even played with the volume:

volume = bot.getProperty('volume')
print(f"Current volume: {volume}")
bot.setProperty('volume', 0.5) # Range is 0.0 to 1.0

bot.say("This is spoken at half volume.")
bot.runAndWait()

Loop to Read Multiple Sentences

Finally, I made Python read a list of lines great for practicing paragraph reading:

sentences = ["Welcome to Python", "Text to speech is fun", "Practice makes perfect"]

for line in sentences:
bot.say(line)

bot.runAndWait()

Final Thought

This mini project made me realize just how powerful and fun Python can be. From simply saying “Hello World” to creating an actual voice assistant foundation, the possibilities are endless.

Related blog posts