To convert text to speech in Python, you can use the
pyttsx3 library. This library provides a simple and convenient way to generate speech from text. Here’s an example:
First, make sure you have the
pyttsx3 library installed by running
pip install pyttsx3 in your command line.
import pyttsx3 # Create a text-to-speech engine engine = pyttsx3.init() # Set the properties of the speech engine.setProperty('rate', 150) # Speed of speech (words per minute) engine.setProperty('volume', 0.8) # Volume level (0.0 to 1.0) # Enter the text you want to convert to speech text = "Hello, world! This is a test." # Convert the text to speech engine.say(text) # Play the speech engine.runAndWait()
In this example, we first import the
pyttsx3 library and create a text-to-speech engine using the
Next, we set the properties of the speech using the
setProperty() method. Here, we adjust the rate (speed) of the speech and the volume level according to your preference.
Then, we define the
text variable with the text you want to convert to speech.
say() method is used to convert the text to speech. It accepts the
text as an argument.
Finally, we use the
runAndWait() method to play the speech. This method will block the program until the speech is complete.
When you run the code, you should hear the text spoken aloud using the default system voice.
Note that the available system voices may vary depending on your operating system and configuration. You can use the
engine.getProperty('voices') method to get a list of available voices and select a specific voice by setting
pyttsx3 library provides various other methods and options for more advanced text-to-speech functionality, such as changing the voice, saving the speech to a file, or adding pauses and custom pronunciation. Refer to the
pyttsx3 documentation for more details and advanced usage.