The objective of this post is to explain how to synthesis a simple speech using Python and the pyttsx module.
Installing the module
We will use pip to install the pyttsx module. Nevertheless, as indicated here, we first need to install the the pywin32-extensions package. Although we can do it using an installer available here, the easiest way is also installing via pip, using the following command:
pip install pypiwin32
Just as a quick explanation, pywin32 provides access to part of the Win32 API .
After this installation, we just need to install pyttsx with the following pip command:
pip install pyttsx
If after the installation, upon running an example, you get the error bellow, just restart the Python shell / editor and try to run it again .
ImportError: no module named win32api
Hello world program
First, we start by importing the previously installed pyttsx module.
After the initial import, we call the init function to get an engine instance for the speech synthesis . If we don’t pass any argument as input of the function, it will use the best driver for the operating system we are using .
voiceEngine = pyttsx.init()
Then, we call the say method on the engine instance, passing as input the text to be spoken.
voiceEngine.say('Hello World! This is a speech synthesis test.')
Finally, we call the runAndWait method, also on the engine instance, to process the voice commands . Check the full code, already with this call, bellow.
import pyttsx voiceEngine = pyttsx.init() voiceEngine.say('Hello World! This is a speech synthesis test.') voiceEngine.runAndWait()
Testing the code
To test the code, just run it, for example, on IDLE. The string defined in the code should now be synthesized and spoken, as indicated in the video bellow. Please note that different versions of the operating system may result in different voices, depending on the underlying speech synthesis engine. Also, in the video bellow, the voice is kind of robotized, probably due to my screen recording software. On my computer, the output is very clean.
- Python version: 2.7.8
- Pyttsx version: 1.1