Text-to-Speech (TTS) means converting written text into spoken audio. In Python, one of the simplest libraries for this task is gTTS (Google Text-to-Speech).
Features of gTTS
- Converts text into speech easily
- Supports multiple languages
- Saves output in MP3 format
- Allows normal or slow speech speed
- Simple and beginner-friendly API
Installation
To install the gTTS library, open the terminal or command prompt and run:
pip install gTTS
Syntax
The basic syntax for gTTS is:
from gtts import gTTS
myobj = gTTS(text="Your text here", lang="en", slow=False)
myobj.save("output.mp3")
Parameters:
- text: The text you want to convert to speech.
- lang: Language code (e.g., 'en' for English).
- slow: True for slow speech, False for normal speed.
- save(): Saves the audio file as MP3.
Example: This program converts text into speech, saves it as an MP3 file, and plays it using your system's default audio player.
from gtts import gTTS
import os
mytext = 'Welcome to GeeksforGeeks Joe!'
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("welcome.mp3")
os.system("start welcome.mp3")
Output
Explanation:
- myobj = gTTS(text=mytext, lang=language, slow=False): Creates a gTTS object using the given text and language, with normal speech speed.
- os.system("start welcome.mp3"): Plays the generated audio file using the system’s default media player.