In this article we will see how to convert text to speech in python and the libraries required by python program to enable this functionality.
Lets start with Offline Text to Speech conversion, to achieve this install pyttsx3 library using the command pip install pyttsx3
import pyttsx3
Initialize the Text to Speech library by invoking init function
TXT2SPCH_ENGINE = pyttsx3.init()
text = "Python programming makes coding simple"
TXT2SPCH_ENGINE.say(text)
To play the converted speech
TXT2SPCH_ENGINE.runAndWait()
This library also provides different properties that can be set on the speech like rate (speed of voice), voice (different types of voices), save_to_file (save speech to a file).
rate = TXT2SPCH_ENGINE.getProperty("rate")
print(rate)
Default rate is 200. Setting any value above 200 sets the voice to a faster rate and value below 200 sets the voice to a slower rate.
faster rate:
TXT2SPCH_ENGINE.setProperty("rate", 300)
slower rate:
TXT2SPCH_ENGINE.setProperty("rate", 100)
Fetch the details of all voices available in the library
voices = TXT2SPCH_ENGINE.getProperty("voices")
Set a new voice to the speech engine
TXT2SPCH_ENGINE.setProperty("voice", voices[1].id)
Saving Speech to file
TXT2SPCH_ENGINE.save_to_file(text, "audioSpeech.mp3")
A sample program with complete details is available at GitHub The program reads the input from a file and converts the text to speech.
No comments:
Post a Comment