Think of an real life scenario where you need text to speech conversion……ok, what about reading a story for you ?
Let us see how simple is this to implement in python. You need gTTS, google text to speech, python module for this. Here is how you install this module
sudo pip3 install gTTS
Since we are saving converted audio in a file, so you also need a command line audio player which you can invoke in python code using “os” module. You can install and use mpg321 or any other player of your choice.
And here is the simple code to convert text into audio. This program will save audio in speech.mp3 file.
#!/usr/bin/python3
from gtts import gTTS
import os
intext = 'Dog is chasing a cat and cat is chasing a mouse. Mouse is running hard to save his life. Thats life !!'
language = 'en'
t2s = gTTS(text = intext, lang=language, slow=False)
t2s.save("speech.mp3")
os.system("mpg321 speech.mp3")
Save above code in text2speech.py and execute as following.
./text2speech.py
High Performance MPEG 1.0/2.0/2.5 Audio Player for Layer 1, 2, and 3.
Version 0.3.2-1 (2012/03/25). Written and copyrights by Joe Drew,
now maintained by Nanakos Chrysostomos and others.
Uses code from various people. See 'README' for more!
THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK!
Playing MPEG stream from speech.mp3 ...
MPEG 2.0 layer III, 32 kbit/s, 24000 Hz mono
[0:07] Decoding of speech.mp3 finished.
Above execution saves audio of text “Dog is chasing a cat and cat is chasing a mouse. Mouse is running hard to save his life. Thats life !!” in speech.mp3 and then plays audio using mpg321 player.