Text To Speech: Part 2/3

Pilahi Moran
2 min readJun 14, 2021

Last week I went on to show how to implement basic text to speech in our Python code with gTTS. Today I’ll go over taking a text file and converting that into audio.

Now, this will be fairly short because there is only one real change in our code and that would be for out text variable.

Previously we wrote out text variable as:

text = "Beep Bleep Imma Sheep I said Beep Bleep Imma Sheep"

Now, that’s all well in good if we are creating the text four our conversion to audio but what if we already have a .txt file? We would use this:

text = open('blog2.txt', 'r').read()

We tell Python we want to both open and read the .txt file blog2.txt. By using this line, we are able to get the text from the file and convert it as we did previously. Further more, we’ll use the rest of our code from last week:

language=’en’
blogoutput=gTTS(text=text,lang=language,slow=False)
blogoutput.save(‘blogoutput.mp3’)
os.system(‘blogoutput.mp3’)

(I renamed fileoutput from last week to blogoutput only from my own differentiation between code used in separate posts)

Once we run it, we’ll see that our audio has been created and your audio should play automatically as before.

This has the potential for audio book or even notes to be converted for the sight impaired! How cool is that?

--

--

Pilahi Moran

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