Search code examples
pythonpyttsx

Can I use a print() function and the speak or say(as in pyttsx3 module) at the same time?


I'm trying to figure out a way so that the text that gets printed on the screen with the print() function also gets spoken at the same time. I am currently using the pyttsx3 module, but I don't see how I can do that.

I didn't knew much about what I can try in this scenario. The code below is just an example code.

import pyttsx
engine = pyttsx.init()

print('Sally sells seashells by the seashore.')
engine.say('Sally sells seashells by the seashore.')

print('The quick brown fox jumped over the lazy dog.')
engine.say('The quick brown fox jumped over the lazy dog.')

engine.runAndWait()

I want the print and engine.say commands to work together.


Solution

  • Use runAndWait() after each sentence.

    Here's what your code could look like if you define a function for that purpose and then iterate over a list of sentences you want to print and speak:

    import pyttsx3
    
    engine = pyttsx3.init() 
    
    def print_and_speak(text):
        print(text)
        engine.say(text)
        engine.runAndWait()
    
    text_list = ['Sally sells seashells by the seashore.',
                 'The quick brown fox jumped over the lazy dog.']
    
    for t in text_list:
        print_and_speak(t)