python pyttsx3 with code examples

Python is one of the most popular programming languages used today, with various libraries and frameworks that aid in its functionality. One such library is pyttsx3, which stands for Python Text to Speech (TTS) version 3. pyttsx3 enables text to be converted to speech, which can be used for various applications, including accessibility and speech recognition systems.

In this article, we will explore pyttsx3 in detail, including how to install it, its features, and different examples of its use.

Installation and Setup

The first step to using pyttsx3 is to install it. You can install it via pip as shown below:

!pip install pyttsx3

After installing, we can import it in our code and start using its features.

import pyttsx3

Features of pyttsx3

  1. Voice Selection

pyttsx3 comes with different voices from various languages that can be used for text to speech conversion. The list of available voices can be obtained using the engine.getProperty('voices') command. To select a particular voice, we use the setProperty method as shown below:

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) # selecting the first voice in the list
  1. Set speed and volume

We can also set the speed and volume at which text is spoken using the commands setProperty('rate', rate) and setProperty('volume', volume) where rate is a floating-point number representing the speed and volume is a float ranging from 0 to 1 representing the volume.

engine.setProperty('rate', 125)    # Setting the speed of the voice
engine.setProperty('volume', 0.7)  # Setting the volume of the voice
  1. Convert text to speech

To convert text to speech, we use the say() method as shown below:

engine.say('Hello World!')
engine.runAndWait()

Here, runAndWait() is a method that waits until all pending commands are executed before continuing with the next instruction.

  1. Queue method

We can also use the addQueue() method to add sentences to be spoken to a queue, and then use the runAndWait() method to execute all the sentences in the queue.

engine = pyttsx3.init()
engine.setProperty('rate', 125)
engine.say('Hello World!')
engine.say('Python is awesome!')
engine.runAndWait()
  1. Event-driven

pyttsx3 is also event-driven. We can define an event listener that listens for an end-of-utterance event, which is triggered when the engine finishes speaking a sentence.

def on_end(name, completed):
    print('ending', name, completed)
engine = pyttsx3.init()
engine.connect('finished-utterance', on_end)
engine.say('Hello World!')
engine.runAndWait()

The on_end() function will be triggered when the finished-utterance event is fired.

Code Examples

  1. Simple Text to Speech Program
import pyttsx3
engine = pyttsx3.init()
engine.say('Hello World!')
engine.runAndWait()

Output:

Hello World!
  1. Using Voice and Speed Control
import pyttsx3 
engine = pyttsx3.init() 
voices = engine.getProperty('voices') 
engine.setProperty('voice', voices[1].id) # Selecting the second voice
engine.setProperty('rate', 125) # Setting the speed of the voice 
engine.say("I'm speaking in Python!") 
engine.runAndWait() 

Output:

I'm speaking in Python!
  1. Text to Speech Using File Input
with open('sample.txt') as f:
    text = f.readlines()
text = [x.strip() for x in text] 
engine = pyttsx3.init()
engine.say(str(text))
engine.runAndWait()

Output:

Hey there! Welcome to the world of Python.

Conclusion

pyttsx3 is a powerful library that provides text to speech conversion functionality to Python applications. It offers a variety of features such as voice selection, speed and volume control, and event-driven programming. With pyttsx3, developers have access to a simple and effective way to convert text to speech, making it a useful tool for speech recognition and accessibility applications.

Installation and Setup

To install pyttsx3, you can use the pip package manager by running the following command in your terminal:

!pip install pyttsx3

Alternatively, you can download the source code from the official repository on GitHub and install it manually. Once installed, you can import it into your Python script using the following line of code:

import pyttsx3

Features of pyttsx3

  1. Voice Selection

pyttsx3 provides a range of voices from different languages that you can use for text to speech conversion. To retrieve the list of available voices, use the command engine.getProperty('voices'). You can select a specific voice by using its ID with the setProperty() method as shown below:

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) # selecting the first voice in the list
  1. Speed and Volume Control

You can adjust the speed and volume of the voice with the setProperty() method. The rate property represents the speed of speech, with 200 as the maximum and 0.1 as the minimum. The volume property ranges from 0 to 1.

engine.setProperty('rate', 125)    # Setting the speed of the voice
engine.setProperty('volume', 0.7)  # Setting the volume of the voice
  1. Convert Text to Speech

To convert text into speech, use the say() method as shown below:

engine.say('Hello World!')
engine.runAndWait()

The runAndWait() method waits for the text to complete before moving on to the next command.

  1. Queuing Method

You can queue up multiple sentences to be spoken using the addQueue() method and then run them using runAndWait().

engine.say('Hello World!')
engine.say('Python is awesome!')
engine.runAndWait()
  1. Event-Driven

pyttsx3 is also event-driven, meaning you can set up event listeners to wait for specific events to occur during text to speech conversion. For example, the finished-utterance event can be triggered when the engine finishes speaking a sentence, as shown below:

def on_end(name, completed):
    print('ending', name, completed)
engine = pyttsx3.init()
engine.connect('finished-utterance', on_end)
engine.say('Hello World!')
engine.runAndWait()

The on_end() function will be triggered when the finished-utterance event is fired.

Code Examples

  1. Basic Text to Speech Program
import pyttsx3
engine = pyttsx3.init()
engine.say('Hello World!')
engine.runAndWait()

This code uses pyttsx3 to convert the text "Hello World!" into speech.

  1. Changing the Voice and Speed of Speech
import pyttsx3 
engine = pyttsx3.init() 
voices = engine.getProperty('voices') 
engine.setProperty('voice', voices[1].id) # Selecting the second voice
engine.setProperty('rate', 125) # Setting the speed of the voice 
engine.say("I'm speaking in Python!") 
engine.runAndWait() 

This code selects the second voice in the voices list (British English), sets the speed of the voice to 125, and converts the text "I'm speaking in Python!" into speech.

  1. Text to Speech from a File
with open('sample.txt') as f:
    text = f.readlines()
text = [x.strip() for x in text] 
engine = pyttsx3.init()
engine.say(str(text))
engine.runAndWait()

This code reads in text from a file named sample.txt, converts it to speech, and then uses pyttsx3 to play the speech.

Conclusion

In summary, pyttsx3 is a powerful library that provides developers with an easy-to-use interface to convert text to speech. With its ability to select different voices, control the speed and volume of speech, and queue up sentences for uninterrupted playback, pyttsx3 is an ideal tool for building text to speech applications. Its event-driven architecture also makes it suitable for building systems that respond to specific events during text to speech conversion. With the help of examples, you can easily get started with using pyttsx3 in your Python projects.

Popular questions

Q1. What is pyttsx3?
A1. pyttsx3 is a Python library that enables text to speech conversion.

Q2. How can I install pyttsx3?
A2. You can install pyttsx3 using the pip package manager by running the command !pip install pyttsx3 in your terminal.

Q3. What are some features of pyttsx3?
A3. Some features of pyttsx3 include voice selection, speed and volume control, event-driven programming, and queuing methods.

Q4. How can I set the speed and volume of speech in pyttsx3?
A4. You can set the speed and volume of speech using the setProperty() method with the rate and volume properties.

Q5. Can I convert text from a file into speech with pyttsx3?
A5. Yes, you can read in text from a file and convert it to speech using pyttsx3, as shown in the example provided in the article.

Tag

TalkPython

My passion for coding started with my very first program in Java. The feeling of manipulating code to produce a desired output ignited a deep love for using software to solve practical problems. For me, software engineering is like solving a puzzle, and I am fully engaged in the process. As a Senior Software Engineer at PayPal, I am dedicated to soaking up as much knowledge and experience as possible in order to perfect my craft. I am constantly seeking to improve my skills and to stay up-to-date with the latest trends and technologies in the field. I have experience working with a diverse range of programming languages, including Ruby on Rails, Java, Python, Spark, Scala, Javascript, and Typescript. Despite my broad experience, I know there is always more to learn, more problems to solve, and more to build. I am eagerly looking forward to the next challenge and am committed to using my skills to create impactful solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top