Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Convert Text to Speech using Python and gTTS

Rohit Kumar Thakur
Python in Plain English
5 min readSep 5, 2021

--

Photo by Maxwell Nelson on Unsplash

Text to Speech Conversion Code with Explanation

Project Setup

virtualenv -p python3.8 textToSpeech
pip install tk  #make sure tkinter installed in your system
pip install playsound
pip install gtts

Code Part

from gtts import gTTS #google text to speech
from playsound import playsound
from tkinter import *
root = Tk()
root.geometry('600x600')
root.title('BUG NINZA')
root.config(bg='white')
Label(root, text = 'TEXT TO SPEECH' , font='arial 20 bold' , bg ='white smoke').pack()Label(root, text ='Enter Text', font ='arial 15 bold', bg ='white smoke').place(x=20,y=60)
#text variable
Msg = StringVar()
#Entry
input_field = Entry(root, textvariable=Msg, width = '60')
input_field.place(x=20, y=100)
def tts():
Message = input_field.get()
speech = gTTS(text = Message)
speech.save('Ninza.mp3')
playsound('Ninza.mp3')
def Exit():
root.destroy()
def Reset():
Msg.set("")
Button(root, text = "PLAY" , font = 'arial 15 bold', command = tts, width =4).place(x=25, y=140)
Button(root,text = 'EXIT',font = 'arial 15 bold' , command = Exit, bg = 'Red').place(x=100,y=140)
Button(root, text = 'RESET', font='arial 15 bold', command = Reset).place(x=175 , y =140)
root.mainloop()
text to speech conversion using gtts python
#import the librariesfrom gtts import gTTS
from playsound import playsound
from tkinter import *
#initialized windowroot = Tk()
root.geometry('600x600')
root.title('BUG NINZA')
root.config(bg='white')
#Labels
Label(root, text = 'TEXT TO SPEECH' , font='arial 20 bold' , bg ='white smoke').pack()
Label(root, text ='Enter Text', font ='arial 15 bold', bg ='white smoke').place(x=20,y=60)# text variable
Msg = StringVar()
#Entry
input_field = Entry(root, textvariable=Msg, width = '60')
input_field.place(x=20, y=100)
#tts functiondef tts():
Message = input_field.get()
speech = gTTS(text = Message)
speech.save('Ninza.mp3')
playsound('Ninza.mp3')
def Exit():
root.destroy()
def Reset():
Msg.set("")
#Buttons
Button(root, text = "PLAY" , font = 'arial 15 bold', command = tts, width =4).place(x=25, y=140)
Button(root,text = 'EXIT',font = 'arial 15 bold' , command = Exit, bg = 'Red').place(x=100,y=140)
Button(root, text = 'RESET', font='arial 15 bold', command = Reset).place(x=175 , y =140)
#infinite loop to run program
root.mainloop()

--

--

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

No responses yet

Write a response