Python Text to Speech Converter (The Simplest Way)

Voice assistants are taking over the world! Most systems have an inbuilt voice assistant from your phone to your TV that carries out your commands or converse with you. Now, there are a lot of code and Artificial Intelligence algorithms behind the most famous voice assistants, but it is not so challenging to start off the process. What about we start with a text-to-speech converter in Python? It might seem tricky, but don't worry because most of the hard work is done by Google's Text-To-Speech module(abbreviated as gTTS), which converts Python strings(text)to mp3 files(speech). Here is how you do it...

As always, the first thing you need to do is install the modules we need. Obviously, we need the gTTS module, which you can install with this link: gTTS Download or just use the command pip install gtts. 

Now, we could also get the playsound module which plays mp3 files. This module will help us automatically hear the converted speech without manually finding and playing the mp3 file. Here is the link: Playsound Module or use the command pip install playsound.

Now, let's get into the actual code. The gTTS code has two parts, the conversion and the file creation. The conversion part takes attributes like text, language, and speed of speaking, and the file-conversion part saves the converted speech in an mp3 file. 

from gtts import gTTS

text = input('Enter the text to convert:') 

text_to_speech = gTTS(text,lang='en',slow=True) #Conversion

text_to_speech.save('hello.mp3') #Saving

Now, the text entered by the user is converted into speech and stored in the file hello.mp3. The gTTS function also has attributes for language. Use this page for the language codes: Languages Supported. You can also change the speed by setting slow to False if you prefer a faster speed. 

Once you get the mp3 file, you can either access it directly or use the Playsound module to play it for you. If you prefer option #2, here is how you do it: 

import playsound as pl

pl.playsound('hello.mp3')

That's all! With barely 6 lines of code, we have a fully functioning text-to-speech converter. How cool is that? Have fun experimenting with the different features of gTTS and listening to your computer talk...

<Note>If you have already installed gTTS before and you find it to be malfunctioning, I suggest you reinstall or update gTTS as new versions have been released recently.</Note>

If you liked this post and found it helpful, Do follow ThePygrammer to be the first to know every time a new post comes out. Feel free to use the comment section below to share your queries. Please share this post with others who might find it helpful. 

You might also like these posts: 






Comments