Python Text To Speech

Posted in category Software on
300 Words ~2 Minute Reading Time • Subscribe to receive updates on Software
Eric David Smith
Software Engineer / Musician / Entrepreneur
Python Text To Speech by Eric David Smith
Click image to view on GitHub

Convert text to speech (audio and mp3, wav, etc) with Python.

If you want to convert text to speech (audio and mp3, wav, etc) with Python, you can use the gTTS library. gTTS (Google Text-to-Speech) is a Python library and CLI tool to interface with Google Translate's text-to-speech API. Write spoken mp3 data to a file, a file-like object (bytestring) for further audio manipulation, or stdout. Or simply pre-generate Google Translate TTS request URLs to feed to an external program.

Here's a quick example of how to use gTTS to convert text to speech:

The Main Code

Located in main.py:

import os
from gtts import gTTS

def text_to_speech(text, lang='en'):
    file = gTTS(text=text, lang=lang)
    filename = 'speech.mp3'
    file.save(filename)

    # play the audio file
    os.system("afplay " + filename)

text_to_speech("Hello, this is a test.")

You can also use gTTS to convert text to speech in other languages:

text_to_speech("Hola, esto es una prueba.", lang='es')

Example Repo

I made an example for you here: https://github.com/erictherobot/text-to-speech

Audio Example

Here's an example of the audio output from the above code which should sound like "Hello, this is a test."

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

If you find this useful as is please let me know. If you find any bugs, please feel free to submit a pull request or open an issue. If you have any questions, you can contact me.

Supporting My Work

Please consider Buying Me A Coffee. I work hard to bring you my best content and any support would be greatly appreciated. Thank you for your support!

Contact


Eric David Smith
Software Engineer / Musician / Entrepreneur
Software

Related Blog Posts

👈 Scroll 👉

Blog Post Tags