Text-To-Speech changing voice in Python
There are several APIs available to convert text to speech in python. One such APIs is the Python Text to Speech API commonly known as the
pyttsx3 is a very easy to use tool which converts the text entered, into audio.
To install the
pyttsx3 API, open terminal and write
pip install pyttsx3
This library is dependent on win32 for which we may get an error while executing the program. To avoid that simply install
pypiwin32 in your environment.
pip install pypiwin32
Some of the important functions available in pyttsx3 are:
- pyttsx3.init([driverName : string, debug : bool]) – Gets a reference to an engine instance that will use the given driver. If the requested driver is already in use by another engine instance, that engine is returned. Otherwise, a new engine is created.
- getProperty(name : string) – Gets the current value of an engine property.
- setProperty(name, value) – Queues a command to set an engine property. The new property value affects all utterances queued after this command.
- say(text : unicode, name : string) – Queues a command to speak an utterance. The speech is output according to the properties set before this command in the queue.
- runAndWait() – Blocks while processing all currently queued commands. Invokes callbacks for engine notifications appropriately. Returns when all commands queued before this call are emptied from the queue.
Now we are all set to write a sample program that converts text to speech.
The output of the above program will be a voice saying, “Hello GeeksforGeeks” and “I’m also a geek”.
Suppose, you want to change the voice generated from male to female. How do you go about it? Let us see.
As you will notice, when you run the above code to bring about the text to speech conversion, the voice that responds is a male voice. To change the voice you can get the list of available voices by getting
voices properties from the engine and you can change the voice according to the voice available in your system.
To get the list of voices, write the following code.
To change the voice, set the voice using
setProperty() method. Voice Id found above is used to set the voice.
Below is the implementation of changing voice.
Now you’ll be able to switch between voices as and when you want. You can try out running a for loop to assign different statements to different voices. Run the code and enjoy the result.
Please Login to comment...