Pyttsx is a cross-platform text-to-speech (TTS) library for Python that assists in converting any text to speech. It supports multiple TTS engines like SAPI on Windows, NSSpeechSynthesizer on Mac, and espeak on Linux.
As it works offline, Pyttsx does not require an internet connection, making it a popular choice for applications that need to convert text to speech locally. In this tutorial, we’ll go over the steps to install and set up Pyttsx in Python.
Step 1: Install Pyttsx3
Pyttsx is now available as pyttsx3, which is an upgraded version compatible with both Python 2.x and 3.x. To install pyttsx3, open your command prompt or terminal and run the following pip command:
1 |
pip install pyttsx3 |
This command will download and install the pyttsx3 package from the Python Package Index (PyPI).
Step 2: Import the Pyttsx3 Library in Your Python Script
Create a new Python script or open an existing one, and import the pyttsx3 library using the following command:
1 |
import pyttsx3 |
Now you can access the pyttsx3 library functions in your Python script.
Step 3: Initialize the TTS Engine
To use pyttsx3, you’ll first need to initialize the text-to-speech engine. Add the following lines of code to your Python script:
1 |
engine = pyttsx3.init() |
This line of code initializes the TTS engine and stores it in the engine variable for future use.
Step 4: Convert Text to Speech
To convert text to speech using pyttsx3, you’ll need to call the say() and runAndWait() methods of the engine. The say() method adds the text to the speech queue, while the runAndWait() method processes the queue and plays the speech. Add the following lines of code to your script:
1 2 |
engine.say("Hello, how are you?") engine.runAndWait() |
This code will convert the text “Hello, how are you?” to speech and play it using the default TTS engine of your operating system.
Full Example Code
Here’s the complete code demonstrating how to use pyttsx3 to convert text to speech:
1 2 3 4 5 6 |
import pyttsx3 engine = pyttsx3.init() engine.say("Hello, how are you?") engine.runAndWait() |
Conclusion
In this tutorial, we’ve covered the installation and usage of the pyttsx3 library in Python for text-to-speech conversion. With pyttsx3, you can easily create offline Python applications that convert any text input to speech, which can be beneficial in various applications such as voice assistants, audiobook readers, and more.