Python gTTS – Text to speech

Today we will be creating a simple python script that will convert text to speech. To do this we will be using the gTTS Python library which is a tool to interface with Google Translate’s text-to-speech API. The script will take text via input and covert this to a speech audio MP3 file.

from gtts import gTTS

tts = gTTS("Hello! Welcome to Scriptopia.")
tts.save('audio.mp3')

The above will convert the text ‘”Hello! Welcome to scriptopia.” in to an audio MP3 file. Next we will add a means of Input to the script.

from gtts import gTTS

while True:
    Text = input("Please enter your text: ")
    tts = gTTS(Text)
    tts.save('hello.mp3')

The above will convert the user input in to an audio MP3 file. Lastly we will go through how one could change the accents in the audio files, our language code will be fixed to English although we could change the top level domain to adjust for any local accents. For example:

English(India)

from gtts import gTTS

while True:
    Text = input("Please enter your text: ")
    tts = gTTS(Text, lang = 'en', tld='co.in')
    tts.save('hello.mp3')

English(Ireland)

from gtts import gTTS

while True:
    Text = input("Please enter your text: ")
    tts = gTTS(Text, lang = 'en', tld='ie')
    tts.save('hello.mp3')

English(Australia)

from gtts import gTTS

while True:
    Text = input("Please enter your text: ")
    tts = gTTS(Text, lang = 'en', tld='com.au')
    tts.save('hello.mp3')

Leave a Reply