Python text to speech conversion


Python text to speech conversion


In order to convert a given text to speech, In python, we use `pyttsx3` module. pyttsx3 is a text-to-speech conversion library in Python. It works offline, and is compatible with both Python 2 and 3.

Use this command for installation:

pip install pyttsx3

Usage:

First we need to import the module `pyttsx3` using import statement. Then we need to initialize it using `init()` function.

After initializing, we need the program to speak using `say()` function. This takes two arguments as below:

say(text, name string)

text : Any text you wish to hear.
name : To set a name for this speech. (optional)

To run the speech we use runAndWait(). The say() function texts won’t be said unless the interpreter encounters runAndWait().

Example Code #1:


# importing the pyttsx library 
import pyttsx3 
  
# initialisation 
engine = pyttsx3.init() 
  
# testing 
engine.say("Hello world")
engine.say("My first code on text-to-speech")
engine.runAndWait() 



We can also change voice (Male or Female) and manage volume control, Also, we can increase or decrease voice rate.

Example Code #2:


Changing Voice, Volume and Voice rate:

import pyttsx3
engine = pyttsx3.init() # object creation

""" RATE"""
rate = engine.getProperty('rate')   # getting details of current speaking rate
print (rate)                                         # printing current voice rate
engine.setProperty('rate', 125)      # setting up new voice rate


"""VOLUME"""
volume = engine.getProperty('volume')   # getting to know current volume level (min=0 and max=1)
print (volume)                                               # printing current volume level
engine.setProperty('volume',1.0)     # setting up volume level  between 0 and 1


"""VOICE"""
voices = engine.getProperty('voices')           # getting details of current voice
#engine.setProperty('voice', voices[0].id)  # changing index, changes voices. o for male
engine.setProperty('voice', voices[1].id)     # changing index, changes voices. 1 for female

engine.say("Hello World!")
engine.say('My current speaking rate is ' + str(rate))
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
engine.stop()

Comments

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb

Add and delete columns dynamically in an HTML table