Convert Text to Speech in Python (original) (raw)
Last Updated : 21 Aug, 2024
There are several APIs available to convert text to speech in Python. One of such APIs is the Google Text to Speech API commonly known as the gTTS API. gTTS is a very easy to use tool which converts the text entered, into audio which can be saved as a mp3 file. The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. The speech can be delivered in any one of the two available audio speeds, fast or slow. However, as of the latest update, it is not possible to change the voice of the generated audio.
Installation
To install the gTTS API, open terminal and write
pip install gTTS
**Example 1: Using Python OS
Python `
Import the required module for text
to speech conversion
from gtts import gTTS
This module is imported so that we can
play the converted audio
import os
The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks Joe!'
Language in which you want to convert
language = 'en'
Passing the text and language to the engine,
here we have marked slow=False. Which tells
the module that the converted audio should
have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
Saving the converted audio in a mp3 file named
welcome
myobj.save("welcome.mp3")
Playing the converted file
os.system("start welcome.mp3")
`
**Output
The output of the above program should be a
voice saying, 'Welcome to geeksforgeeks Joe!'
**Example 2: Uisng Python Pygame
This works for any platform. Now we are all set to write a sample program that converts text to speech.
Python `
Import the required module for text
to speech conversion
from gtts import gTTS
Import pygame for playing the converted audio
import pygame
The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks!'
Language in which you want to convert
language = 'en'
Passing the text and language to the engine,
here we have marked slow=False. Which tells
the module that the converted audio should
have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
Saving the converted audio in a mp3 file named
welcome
myobj.save("welcome.mp3")
Initialize the mixer module
pygame.mixer.init()
Load the mp3 file
pygame.mixer.music.load("welcome.mp3")
Play the loaded mp3 file
pygame.mixer.music.play()
`
Output
The output of the above program should be a
voice saying, 'Welcome to geeksforgeeks!'