Google text-to-speech : example of GUI to create mp3 from text

Wanna create mp3 from text easily?

text-to-speech
The app that will appear when you run the code

The mp3 file generated in the example

Here is what you need. In the following code we will use the gtts module to use the google text to speech API and create a file in a language of your choice. All this from python, using tkinter module to create the graphic interface.

Here is the code

"""Use gtts with Python.

Create mp3 from text with python, tkinter and gtts
2018
@ Giovanni Gatto
"""

# A PROGRAM FROM GIOVANNI GATTO AKA EDUCATIONAL CHANNEL ON YOUTUBE
# AKA PYTHONPROGRAMMI ON TWITTER
# published on http://pythonprogramming.altervista.org

from gtts import gTTS
import os
import tkinter as tk

root = tk.Tk()
root.geometry("400x200+200+600")

# THE ACTION LINKED TO THE EVENT LISTENER
def gorun():
    s = gTTS(t.get(), lang=lan.get())
    s.save(f"{mp3.get()}.mp3")
    filename = mp3.get() + ".mp3"
    os.system("start " + filename)

# THE FIRST LABEL TELLS YOU WHAT TO DO TO MAKE IT WORK
title = tk.Label(root, text="PRESS ENTER TO HEAR THE TEXT")
title.pack()
title['bg'] = 'yellow'
t = tk.StringVar()

# WHERE YOU WRITE THE TEXT
text = tk.Entry(root, textvariable=t, width=50)
text.pack()
t.set("Example of text")

# THE LANGUAGE
    # THE LABEL
l2 = tk.Label(root, text="Choose language (default is english=en)")
l2.pack()
    # THE ENTRY WIDGET
lan = tk.StringVar()
language = tk.Entry(root, textvariable=lan)
language.pack()
lan.set("en")

# THE NAME OF THE FILE
mp3 = tk.StringVar()
mp3title = tk.Entry(root, textvariable=mp3, width=50)
mp3title.pack()
mp3.set("myfile")

# THE EVENT LISTENER
root.bind("<Return>", lambda x: gorun())

root.mainloop()

Tkinter test for students

Tkinter articles

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.