From text to mp3 with gtts (reading external file)

Today I am gonna show you how to create an mp3 file from text reading an external file. As usual, we will do the simple things first and then we will add some features to it.

How we can even do it?

We have to thank Google to provide us this API to get the chance to transform text in audio, otherwise it would be very difficult to do it. The module gtts makes very easy to do it and the great thing is that you can do it for every language. In practise we take advantage of google translate tools. So, aren’t you excited to know everything about it? I remember that I did something about mixing different languages in the same audio file in an easy way, but I think I lost the script. Maybe I could try to check again the way to do that …

Let’s show the code

Let’s see how is the fastest way to do it.

First things first, you have to install gtts to do what we said previously:

Let’s make something basic

from gtts import gTTS
ttmp3 = gTTS("Hello World", "en")
ttmp3.save("hello.mp3")

This is the mp3 generated

Let’s Play the mp3 using python itself, with the module os and the startfile function to launch the file with the default mp3 player

import os

from gtts import gTTS
ttmp3 = gTTS("Hello World", "en")
ttmp3.save("hello.mp3")

os.startfile("hello.mp3")

Convert text from a file

Now, answering to a request, we are going to convert in audio the text that is present in a file.

We need with open to open the file and the read method to read the content. Then, as usual we will ask gtts to do the work for us, converting the text. We will save it at the end.

Save some text in a file called, for example, text.txt (what an original name!), like this:

This text comes from a file called text
This code has been powered by Google
Visit pythonprogramming.altervista.org

Then save a file called tts_from_file.py with this code

import os
from gtts import gTTS

with open("text.txt") as file:
	t = gTTS(file.read(), "en")
t.save("text.mp3")

os.startfile("text.mp3")

This is the result (just in case…)

Exagerating

With some simple changes we could make different files in no time.

More mp3 from all files in the dir

Let’s save another text file called text2.txt, with some text like the one below:

This is the second file
of text and will
generate
another mp3 file,
save as many file as you want
and you will have an mp3 for each one

Let’s write this code to a py file:

import os
from gtts import gTTS
from glob import glob

for f in glob("*.txt"):
	with open(f) as file:
		t = gTTS(file.read(), "en")
	t.save(os.path.splitext(f)[0] + ".mp3")

for f in glob("*.mp3"):
	os.startfile(f)

Python will make a list of all txt file in the folder where the python file is, will read the first and convert to audio, save it and so on for every file in the list. Each new file will have the same name of the txt file, with mp3 as extension.

We will have, at the end, two files. For every txt file we add in the folder we will have the mp3 that we just know (from text.txt) and another mp3 (from text2.txt):

the first (heard yet)

the second (new)

What if: All text from different files in one mp3

Now we want to make one mp3 with all the text from different text files… Is it clear?

Thats the code:

import os
from gtts import gTTS
from glob import glob

t = ""
for f in glob("*.txt"):
	with open(f) as file:
		t += file.read()
tts = gTTS(t, "en")
name = "full.mp3"
tts.save(name)
os.startfile(name)

This is the full.mp3 (text + text2)

What if: more mp3 from 1 txt file

This time we do the opposite we create more mp3 from 1 text file? How? Making an mp3 for every line of txt, for example. The names will have a progressive number at the end.

Let’s see how (let me write down some strategy lines).

  • I will open the file (let’s say a new text file called numbers.txt with numbers from 1 to 5)
  • I will loop every line (see it in the code below)
  • then I will “gTTS” all the lines and save them
  • at the end with a loop and os.startfile I’ll launch all the mp3 to hear if all’s gone right
  • then I’ll come back here and post the audio as a proof of the successful output

save numbers.txt

1
2
3
4
5

save manymp3.py

import os
from gtts import gTTS
from glob import glob

lst = []

with open("number.txt") as file:
	for n,line in enumerate(file):
		tts = gTTS(line,"en")
		name = "number" + str(n) + ".mp3"
		tts.save(name)
		lst.append(name) # this is just to hear them with os....

[os.startfile(name) for name in lst]

This is the window that opens in my pc, you can see the file name with different numbers. We can add 1 to n in the code if we want to have number 1 for “one”… etc. You know that lists, like arrays, starts from 0… that is why we have that. I used enumerate in the for loop to have two variables from the iteration of the list: the number of the index and the string (in this case) of each item of the list with the names of the file generated.

There they are the different audio files with each line of text converted (this time just numbers)

one

two

three

four

five

As this are numbers we could easily do this for many languages.

Let’s do an example for english and italian.

P.S.: to save time I limited numbers to 1,2 and 3:

We just have to:

  • add a list with languages shortcut
  • add a for loop of the language outside the loop we’we seen above
  • add the variable of the language loop to replace “en” in gTTS istances
  • add the l variable to the name of the mp3 to distinguish italian from english numbers

that’s all

import os
from gtts import gTTS
from glob import glob

lst = []
lan = ["en", "it"]
for l in lan:
	with open("numbers.txt") as file:
		for n,line in enumerate(file):
			tts = gTTS(line, l)
			name = "number" + l + str(n) + ".mp3"
			tts.save(name)
			lst.append(name) # this is just to hear them with os....
			print(f"saved {name}")
[os.startfile(name) for name in lst]

The output is in this video

And these are the files created with that code in one step:

One, two and three

Uno, due e tre

What next?

Ok, we’ve seen some stuff that we could do with gtts and a little amount of fantasy. Thanks to the one that suggest me to explain the use of this module that give the start to make this post. As you can see from something we can do something else that is very different from the starting point. This could be used to make a learning language app… or anything that comes into your mind.

The next step will probably be to build a GUI… as I often do… from script to GUI.

Here is an example of what we could do:

  • create a listbox with the text in a folder to select wich one to transform in mp3
  • put a checkbox to choose if you want different mp3 for each file or just one
  • another to make an mp3 for every line of a single txt file
  • an entry to choose the language

This stuffs could be done… or remain theory… who knows?

To be continued…

How to convert text to mp3 from external file video

Utilities

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.