Convert text to speech using pyttsx3

Posted by Afsal on 10-Nov-2023

Hi Pythonistas!

Today we will learn about a library that converts text to speech which is called pyttsx3. Main advantage of this library is it works offline. Feature of this packages are

  • ✨Fully OFFLINE text to speech conversion
  • Choose among different voices installed in your system
  • Control speed/rate of speech
  • Tweak Volume
  • Save the speech audio as a file
  • ❤️ Simple, powerful, & intuitive API

Let us dive into the code

Installation

pip install pyttsx3

If you are using linux

 sudo apt update && sudo apt install espeak ffmpeg libespeak1

Single line usage with default settings

import pyttsx3

pyttsx3.speak("I will speak this text")

Basic usage

import pyttsx3

engine = pyttsx3.init()

engine.say("I will speak this text")

engine.runAndWait()

Advanced usage

import pyttsx3
engine = pyttsx3.init() 

""" 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[1].id)   #changing index, changes voices to second item in the list

engine.say("Hello World!")
engine.say('My current speaking rate is ' + str(rate))
engine.runAndWait()
engine.stop()

"""Saving Voice to a file"""
engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()

getProperty - This will return the current value of the property.

eg getProperty('volume')  this will returns the current volume

setProperty - This is used to set new value to the property

eg engine.setProperty('volume',1.0) , this set new value for the volume property

engine.save_to_file('Hello World', 'test.mp3') - When this code is executed a new mp3 file created with name test.mp3 and content of this file s hello world sound

For more details you can check the full documentation of this library.

Hope you have learned something new from this post. Please share your valuable suggestions with afsal@parseltongue.co.in