Text-to-Speech in Python Using pyttsx3
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:
- Importing pyttsx3: Begin by importing the
pyttsx3
library, which provides text-to-speech functionality. - Initializing the Engine: Create an instance of the text-to-speech engine using
pyttsx3.init()
. - Setting Volume: Retrieve and set the volume of the text-to-speech engine using
engine.getProperty('volume')
andengine.setProperty('volume', 0.9)
. - Getting Available Voices: Get a list of available voices with
engine.getProperty('voices')
. - Selecting a Voice: Choose a voice from the available list and set it using
engine.setProperty('voice', voices[0].id)
. - Setting Speech Rate: Adjust the speech rate with
engine.getProperty('rate')
andengine.setProperty('rate', 100)
. - Converting Text to Speech: Specify the text you want to convert to speech with
engine.say()
. - 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 !!!