
Voice Generation for Python Developers
Welcome to the world of text-to-speech synthesis! Python’s GTTS library offers a simple yet powerful way to convert written text into spoken words. In this beginner-friendly guide, we’ll explore GTTS, diving into its functionalities to generate speech from text using Google’s API. By the end, you’ll be equipped to create speech-enabled applications and tools using Python.
Google’s Text-to-Speech Library
To use Google’s Text-to-Speech (TTS) service with Python, you can utilize the gTTS
(Google Text-to-Speech) library. Here’s a step-by-step guide on how to get started:
Installation:
Install the gTTS
library by running the following command in your terminal or command prompt:
pip install gTTS
Step-By-Step Coding Guide
Once the installation is complete, you can import the library into your Python script:
from gtts import gTTS
Create an instance of the gTTS
class and provide the text you want to convert into speech:
text = "Hello, how are you?" tts = gTTS(text)
Optionally, you can specify the language (default is English) and the slow speed of speech (default is False) by passing arguments to the gTTS
constructor:
tts = gTTS(text, lang='en', slow=False)
Save the audio file by calling the save()
method on the gTTS
instance and providing the desired filename:
filename = "output.mp3" tts.save(filename)
You now have an MP3 file containing the synthesized speech. You can play it using a media player or integrate it into your application as needed.
Python Code Example
Here’s the complete code:
from gtts import gTTS text = "Hello, how are you?" tts = gTTS(text) filename = "output.mp3" tts.save(filename)
That’s it! we have successfully used Google’s Text-to-Speech service with Python to convert text into speech and save it as an MP3 file.
Conclusion
Congratulations on discovering Python’s GTTS library! You’ve unlocked a powerful tool for converting text to speech, opening doors to innovative applications and accessibility solutions. As you continue your exploration, experiment with various text inputs and voice settings GTTS offers. With GTTS, you have the capability to infuse speech into your Python projects effortlessly.
That’s All Folks!
You can explore more of our Python guides here: Python Guides