In this tutorial, we’ll cover how to install and use the Google Text-to-Speech (gTTS) library in Python.
gTTS is a useful library that allows you to convert text to speech using the Google Text-to-Speech API.
It’s perfect for creating audio files, integrating voice notifications into your applications, or even building your very own text-to-speech assistant.
Step 1: Install Python
Before you can start using gTTS, you’ll need to have Python installed on your computer. You can download the latest version of Python from the official website.
Follow the instructions provided to install Python on your operating system.
Step 2: Install gTTS
Once you have Python installed, you can proceed to install the gTTS library. Open your command prompt or terminal and enter the following command:
1 |
pip install gtts |
pip will automatically download and install the gTTS library and its dependencies for you.
Step 3: Create a Python Script
Now that you have gTTS installed, create a new Python script file (e.g., text_to_speech.py
) using your preferred text editor or IDE.
Step 4: Import gTTS
In your Python script, import the gTTS module by adding the following line at the top of your file:
1 |
from gtts import gTTS |
Step 5: Write Your Text-to-Speech Code
Now, you can write a simple script that takes a text input and converts it into an audio file using gTTS. Here’s a basic example:
1 2 3 4 5 6 7 |
text = "Hello, this is a test of the gTTS library." # Create a gTTS object tts = gTTS(text=text, lang='en', slow=False) # Save the audio file as an MP3 tts.save("output.mp3") |
In this example, we specify the text, language (English), and speed (not slow) of the speech. We then save the generated speech as an MP3 file named output.mp3
.
Step 6: Run Your Script
Now, you can run your Python script by entering the following command in your terminal or command prompt:
1 |
python text_to_speech.py |
Once the script finishes executing, you should find an output.mp3
file in the same directory as your script. You can play this file to listen to the generated speech.
Full Code:
1 2 3 4 5 6 |
from gtts import gTTS text = "Hello, this is a test of the gTTS library." tts = gTTS(text=text, lang='en', slow=False) tts.save("output.mp3") |
Conclusion
With the help of the gTTS library, you can easily create audio files from text or add speech capabilities to your Python applications.
This tutorial covered the basics of installing and using gTTS, but there are additional options and features you may find useful for your projects. Check out the official documentation for more details and examples.