It is always a hazard to make a program capable to speak without an internet connection in any programming language. However, to our rescue we are gonna use python, and to further help our situation, we will be using a python library pyttsx3. Which is a text-to-speech library.
What will you need?
- Python 3 above, but you can also use python 2.
- A proper installation of pip3 or similar.
- Basics of python.
- Windows machine. To cover other operating systems(embedded systems, linux, and mac) is out of scope for this blog post.
With all the ingredients ready, lets start!
Step 1: Install pyttsx3.
First, we will be using pip to install pyttsx3. So open up your command prompt, and type the following.
pip3 install pyttsx3
Step 2: Coding your way out.
Now, we will look at the code necessary for your AI to speak some magical words. We implement the logic by the below painstaking code.
Line 1 :-
In the first line we import pyttsx3. Do remember that when importing a library as whole, it is imported as an object. And it’s functions are imported as its method.
Line 2 :-
The next line returns an object created by init method, defined in pyttsx3 library. This object contains important methods, that we can use to modify our voice, or speech rates and etc etc.
Line 3 :-
The third line pushes a speak command in the command queue. This queue can contain a list of commands to be executed by our engine, in this case an AI.
Line 4 :-
The last line will command the engine to execute every command placed in the command queue. It will also kinda “pause” the control of program, as it happens with other control statements like loops and functions.
Be ready to hear those three golden words, “I can speak!”.
In the next article/story, I will cover how to modify, add a custom voice, or adjust speech rate. Stay tuned, more articles are coming.
Thanks for reading.
Give your program the ability to speak without requiring an internet connection. was originally published in Python Pandemonium on Medium, where people are continuing the conversation by highlighting and responding to this story.