Python gtts change voice

Explaining how to change voice in Python GTTS

In order to change the voice using Python GTTS (Google Text-to-Speech), you need to understand a few concepts and utilize the available methods and parameters.

Step 1: Install the necessary packages

First, make sure you have the required packages installed. Use pip to install the following:

pip install gTTS pyttsx3

Step 2: Import the required modules

In your Python script, import the necessary modules:

from gtts import gTTS

Step 3: Create a gTTS object

Create a gTTS object and specify the text you want to convert to speech:

tts = gTTS('Hello, how are you?')

Step 4: Save the audio to a file

Save the audio to a file using the save() method:

tts.save('output.mp3')

Step 5: Change the voice with pyttsx3

If you want to change the voice, you can use the pyttsx3 library. First, import the module:

import pyttsx3

Step 6: Change the voice settings

Create a pyttsx3 object and set the desired voice by changing the voice ID:

engine = pyttsx3.init()
voices = engine.getProperty('voices')
voice_id = 'voice_id_of_your_choice'
engine.setProperty('voice', voice_id)

Step 7: Convert text to speech with the new voice

Now you can convert text to speech using the modified voice:

engine.say('Hello, how are you?')
engine.runAndWait()

Example

Here’s a complete example of changing the voice in Python GTTS:

from gtts import gTTS
import pyttsx3

# Create gTTS object
tts = gTTS('Hello, how are you?')

# Save audio to a file
tts.save('output.mp3')

# Change the voice with pyttsx3
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
voice_id = 'voice_id_of_your_choice'
engine.setProperty('voice', voice_id)

# Convert text to speech with new voice
engine.say('Hello, how are you?')
engine.runAndWait()

Leave a comment