DEV Community

Po
Po

Posted on

Text to speech using Python gTTS in 5 lines of Code

Google text to speech is a life saver when it comes to converting text to speech. Today,we will learn the recipe to cook the above title using Python.You can have a look at the youtube video also.
First of all, we need to have a pan,in this case, it will be gTTS module, To install gTTS and to use it, we need to type the below command.

pip install gTTS
Enter fullscreen mode Exit fullscreen mode

Once you are done with this ,I will suggest to install playsound ,so as to directly play the mp3/wav file.

pip install playsound
Enter fullscreen mode Exit fullscreen mode

Now the installation part is done and pan is ready to cook. Type in the below code in your jupyter notebook code cell.

from gtts import gTTS 
from playsound import playsound 
text =  This is in english language 
var = gTTS(text = text,lang = en) 
var.save(eng.mp3) playsound(.\eng.mp3)
Enter fullscreen mode Exit fullscreen mode

I know that I said that we will do it in 5 lines,and indeed we can, We can directly pass the string (text) in the gTTS function! But thats not important,whats important is to understand what is happening under the hood. The beauty of most python modules is that they are self explaning, I am pretty sure that you must have understood all of it if you have basic knowledge of Python.

We also have some additional parameters which we can pass to make the mp3/wav file more intresting. Some of them are:

slow (bool, optional) — Reads text more slowly. Defaults to False.

lang_check (bool, optional) — Strictly enforce an existing lang, to catch a language error early. If set to True, a ValueError is raised if lang doesn’t exist. Setting lang_check to False skips Web requests (to validate language) and therefore speeds up instanciation. Default is True.

lang (string, optional) — The language (IETF language tag) to read the text in. Default is en.

To pay sound in hindi, all we need is hindi text and we can specify like

gTTS(text="यह हिंदी में एक उदाहरण है",lang='hi')
Enter fullscreen mode Exit fullscreen mode

and that all !

I will be back again but for now, “Stay safe and learn”.
If you have any doubt then watch this youtube video:

Top comments (0)