简体   繁体   中英

Can I run two lines of python code at the same time? (Threading doesn't work)

I want a input from the user, input() function will prompt in the terminal but I want to 'text to speech' that prompt at the same time (simultaneously).

if threading works please answer that in the comments for these code:

import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty('rate', 180)  # Initialising 
# Pyttsx3 Engine

def speak(audio):
   engine.say(audio)
   engine.runAndWait()

q1 = input(f"You're in the dorm. {question()} 
     (stairs up/stairs down) ")

speak(q1)

'q1' should be at executed simultaneously with 'speak(q1)' where the f-string should be spoke. (inside input())

You can use threads like that.

import pyttsx3
import threading
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty('rate', 180)  # Initialising 
# Pyttsx3 Engine

def speak(audio):
   engine.say(audio)
   engine.runAndWait()
while True:
    q1 = input(f"You're in the dorm. {question()} 
         (stairs up/stairs down) ")

    t_handle = threading.Thread(speak, args=(q1,))
    t_handle.start()

pyttsx3 exports a function that runs event loop. You can start that function in a different thread.

thread = threading.Thread(target=engine.startLoop)
# This will start event loop
thread.start()

# from now on running speak will output voice immediately
# without calling .runAndWait()

engine.speak("test")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM