Text-to-Speech in Python Using pyttsx3

Avnish Kumar Thakur
1 min readOct 21, 2023

--

Introduction:

In this tutorial, we’ll explore the pyttsx3 library, a powerful tool for adding text-to-speech capabilities to your Python applications. We'll break down a simple code example and explain each line step by step.

import pyttsx3
engine = pyttsx3.init()
volume = engine.getProperty('volume')
engine.setProperty('volume', 0.9)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
rate = engine.getProperty('rate')
engine.setProperty('rate', 100)
engine.say("Jeetega bhai jeetega, India jeetega")
engine.runAndWait()

Code Explanation:

  1. Importing pyttsx3: Begin by importing the pyttsx3 library, which provides text-to-speech functionality.
  2. Initializing the Engine: Create an instance of the text-to-speech engine using pyttsx3.init().
  3. Setting Volume: Retrieve and set the volume of the text-to-speech engine using engine.getProperty('volume') and engine.setProperty('volume', 0.9).
  4. Getting Available Voices: Get a list of available voices with engine.getProperty('voices').
  5. Selecting a Voice: Choose a voice from the available list and set it using engine.setProperty('voice', voices[0].id).
  6. Setting Speech Rate: Adjust the speech rate with engine.getProperty('rate') and engine.setProperty('rate', 100).
  7. Converting Text to Speech: Specify the text you want to convert to speech with engine.say().
  8. Playing the Speech: Execute engine.runAndWait() to play the speech based on the text you provided.

Conclusion

We explored how to use pyttsx3 for text-to-speech in Python, covering engine initialization, setting volume and speech rate, voice selection, and text-to-speech conversion. Armed with this knowledge, you’re now ready to create Python applications that communicate through speech.

Happy coding !!!

--

--

Avnish Kumar Thakur

Software Engineer | Tech Enthusiast | Linux, DevOps, ML, Python, Java, C | AWS | Generative AI | Researcher | Vlogger | Uncovering Tech's Depths