我正在用Python制作一个语音识别程序,我希望当我说“上面”时,它会连续运行循环以按下向下键,直到我再次不说上面,但现在在我包含线程来制作语音识别器连续运行,整个主循环不识别资源
from speech import *
import queue
import threading
import pyautogui
import keyboard
import time
import sys
def speech_func(res_queue):
while True:
res = speech()
res_queue.put(res)
res_queue = queue.Queue()
prc=threading.Thread(target=speech_func, args=(res_queue,))
prc.start()
flower_active=False
while True:
res = res_queue.get()
if "above" in res:
flower_active = not flower_active
while flower_active:
keyboard.press_and_release('down')
time.sleep(0.1)
if "after" in res:
pyautogui.moveTo(1010,130)
pyautogui.click()
if "before" in res:
pyautogui.moveTo(890,130)
pyautogui.click()
if "music" in res:
pyautogui.moveTo(1680,130)
pyautogui.click()
if "below" in res:
keyboard.press_and_release('pageup')
if "ending" in res:
prc.join()
sys.exit(0)
如果我删除线程,一切都会正常工作,除了向下箭头,当我说“上面”时,它将开始运行循环,但即使我再次说“上面”也不会停止
while flower_active:
正在阻止所有代码,因此无法从队列中获取下一个命令。它需要在单独的线程中运行while flower_active:
。并且可能需要其他队列来停止循环并退出线程。
您也可以尝试使用
if
代替while
然后while True
会重复
while True:
# ... code ...
if flower_active:
keyboard.press_and_release('down')
time.sleep(0.1)
但是还有其他问题:
res_queue.get()
等待数据并且它会阻塞代码,并且可能需要在if not res_queue.empty()
之前检查
.get()
while True:
if not res_queue.empty():
res = res_queue.get()
if "above" in res:
flower_active = not flower_active
elif "after" in res:
pyautogui.moveTo(1010,130)
pyautogui.click()
elif "before" in res:
pyautogui.moveTo(890,130)
pyautogui.click()
elif "music" in res:
pyautogui.moveTo(1680,130)
pyautogui.click()
elif "below" in res:
keyboard.press_and_release('pageup')
elif "ending" in res:
prc.join()
sys.exit(0)
# --- outside of `if not res_queue.empty():`
if flower_active:
keyboard.press_and_release('down')
time.sleep(0.1)
我没有测试过。