Text to speech converting modules by python

Text to speech converting modules by python

Today, I have practised two modules. One is pyttsx3(python text to speech) which is an offline based module. Another one is online-based modules, which is gtts(Google text to speech).

Firstly, I am writing about the pyttsx3 module what I understand.

The 'pyttsx3' or python text to speech version 3 is an offline based speech simulation module. Using this module I could change speaking rate, volume and gender voice. Let's try to fathom with practical code,

import pyttsx3
myText = "Hello I know your Identity" #Define the text

The init() function initialize Text-to-Speech engine

engine = pyttsx3.init()

The getProperty function use to get number details about current speaking rate,volume(min = 0 and max=1) and voices(Male or Female). On the other hand, the setProperty() use to set the value for speaking rate, the value of voice and assign the gender.

rate = engine.getProperty('rate')
print(rate)
engine.setProperty('rate', 150)

volume = engine.getProperty('volume')
print(volume)
engine.setProperty('volume', 0.8)

voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id) # zero for male and one for female

The 'say' function used to convert the Text to Speech. To save the voice in an mp3 format is used the 'sace_to_file' function. Additionally, the 'runAndWait' function has been used to play the mp3 file.

engine.say(myText)
engine.save_to_file(myText, 'test.mp3')
engine.runAndWait()


The last one is the 'gtts' or Google Text to Speech module is an online base simulating module, which simulates human speech during Text to Speech conversion. The os or Operating System module has been using to communicate with the system.

from gtts import gTTS
import os

The 'gTTS' function takes more parameters, But I have used here only three parameters. The first parameter contains the text to read, the 'lang' used to select a language and the 'slow' parameter is to read the text more slowly. There are 60 different languages to assign the 'lang' parameter's variable.

myText = "I know your identity"
output = gTTS(myText, lang='en', slow='false')

Using the 'save' function we just save the converted speech into mp3 format. The 'system' function is called to play that save audio file defined by the path.

output.save('test.mp3')
os.system('start test.mp3')

To get the source code or run, just click.

do you have knowledge of Python 3? which library being used?

Like
Reply

To view or add a comment, sign in

More articles by Abu Nayem

Explore content categories