Last Modified : Friday, April 19, 2024
pyttsx3 is a python library which is used for converting text to speech. Pyttsx3 supports more than 60 voices (Learn more about it here - Supported Voices).
Table of content
Installation
NOTE: We are using conda to install pyttsx3 for python 3.8.19 and this code is tested on ubuntu 16.04 LTS
Let's start by installing pyttsx3 library.
pip install pyttsx3
Along side python library for linux systems we will install additional linux packages
sudo apt install espeak ffmpeg libespeak1
Now to see if the installation is correctly working or not we will start a python shell and test it
python3
Now import following packages in the shell to see if it is working or not
import pyttsx3
engine = pyttsx3.init()
If you don't get any errors from above command then your have sucessfully installed pyttsx3
Getting started
Now that pyttsx3 is installed and running, let's convert our text to speech
import pyttsx3
engine = pyttsx3.init()
engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()
Above code will generate a test.mp3 in your folder.
List all the supported voices
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices') #getting details of current voice
voice_names = [voice.name for voice in voices]
print(voice_names)
You will see following output, these are all the supported voices in pyttsx3
['afrikaans', 'aragonese', 'bulgarian', 'bosnian', 'catalan', 'czech', 'welsh', 'danish', 'german', 'greek', 'default', 'english', 'en-scottish', 'english-north', 'english_rp', 'english_wmids', 'english-us', 'en-westindies', 'esperanto', 'spanish', 'spanish-latin-am', 'estonian', 'persian', 'persian-pinglish', 'finnish', 'french-Belgium', 'french', 'irish-gaeilge', 'greek-ancient', 'hindi', 'croatian', 'hungarian', 'armenian', 'armenian-west', 'indonesian', 'icelandic', 'italian', 'lojban', 'georgian', 'kannada', 'kurdish', 'latin', 'lingua_franca_nova', 'lithuanian', 'latvian', 'macedonian', 'malayalam', 'malay', 'nepali', 'dutch', 'norwegian', 'punjabi', 'polish', 'brazil', 'portugal', 'romanian', 'russian', 'slovak', 'albanian', 'serbian', 'swedish', 'swahili-test', 'tamil', 'turkish', 'vietnam', 'vietnam_hue', 'vietnam_sgn', 'Mandarin', 'cantonese']
How to set a new voice
Above is the list of all the supported voices in pyttsx3, now we will see how to set a new voice and convert a text to speech for that voice
Below code will set an english as a voice and generate a .mp3 file with hello world. You can use above array to set any custom voices. voices[0] is afrikaans and so on.
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[11].id)
engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()
Now try with setting german as a new voice and set Hallo Welt as a text.