Text to Speech in Python: Part 1/3

Pilahi Moran
2 min readJun 7, 2021

First I have to say, the more I use Python the more I understand why many companies use it for their applications (Although I’ll be a Ruby lover for like I think as it was my first coding language learned outside of Html/CSS.)

In the module going over Text to Speech, it was exciting to learn as it could be the beginning of an automated conversion from text to audio books or even be of use to those with visual impairments. So let us get started with a little intro into how to set up your python code for text to speech.

Firstly, you will need to install gtts (Google Text To Speech) module.

pip install gtts 

Once that is in, we will import gtts into our code. We will also need the module os to allow us to open our audio file and play it when the code runs.

from gtts import gTTS
import os

Going forward, we need to define our text we want to convert and the language we will be using. For my example I use my go to phrase to test code.

text=“Beep Bleep Imma Sheep I Said Beep Bleep Imma Sheep”
language=‘en’

After defining our text that we wish to convert, we also define out language as English. I used both the gtts documentation and Goggle’s Cloud of Text-To-Speech languages to make sure I had the correct language code but there are many more to use as well (accent and dialect wise).

From here, we need to use the function we get from gTTS which we assign to a variable to make things easy and save it.

output = gTTS(text=text, lang=language,slow=False)
output.save(‘blog.mp3’)

Now technically that’s it. It’s converted created and saved. But to ensure it truly did as we asked, this is where the use of our os module comes in. Let’s have our code open the file and play it as soon as it is created so that we can hear it.

os.system(‘blog.mp3’)

Once that is done, if we run our code it should create our mp3 and open your system’s player (For Windows 10 that would be Groove Music.)

blog.mp3 was created successfully!

And that’s it! That is the basic method of creating audio from text! Next time I’ll go over converting a text file to audio :) Happy coding!

--

--

Pilahi Moran

Full Stack Software Engineer, Artist, Cook, and Illustrator. Mother of 2 cockatiels and 2 cats.