我希望在我的 Qt 应用程序中实现 QRunnable 和 QThreadPool,我想让 GUI 在后台连续监听麦克风输入。我有线程工作并且它确实运行,但是每当我尝试与 GUI 交互时,程序就会崩溃。
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
class Worker(qt.QRunnable):
def widget(self, m, r):
self.m = m
self.r = r
def run(self):
with self.m as source:
while True:
print("listening")
self.r.adjust_for_ambient_noise(source)
audio = self.r.listen(source)
try:
print(self.r.recognize_google(audio))
# handles any api/voice errors errors
except sr.RequestError:
print("There was an issue in handling the request, please try again")
except sr.UnknownValueError:
print("Unable to Recognize speech")
class VoiceRecognitionWidget(ScriptedLoadableModuleWidget):
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
#Initializes recognizer and microphone
self.recognizer = sr.Recognizer()
try:
self.microphone = sr.Microphone()
except(IOError):
print("ERROR: No default microphone. Check if microphone is plugged in or if you have a default microphone set in your sound settings.")
self.errors.setText("ERROR: No default microphone. Check if your microphone is plugged in or if you have a default microphone set in your sound settings.")
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Parameters"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
self.listenButton = qt.QPushButton("Begin Listneing")
self.listenButton.toolTip = "Listens for voice."
self.listenButton.enabled = True
parametersFormLayout.addRow(self.listenButton)
self.stopButton = qt.QPushButton("Stop Listensing")
self.stopButton.toolTip = "Stops listening."
self.stopButton.enabled = True
parametersFormLayout.addRow(self.stopButton)
self.repeatButton = qt.QPushButton("Repeat last command")
self.repeatButton.toolTip = "Listens for voice."
self.repeatButton.enabled = True
parametersFormLayout.addRow(self.repeatButton)
self.listenButton.connect('clicked(bool)', self.onListenButton)
self.stopButton.connect('clicked(bool)', self.onStopButton)
self.repeatButton.connect('clicked(bool)', self.onRepeatButton)
def onRepeatButton(self):
self.logic.parse("repeat")
def onStopButton(self):
self.stop_listening = True
def onListenButton(self):
slicer.util.delayDisplay("Wait...", 2450)
self.worker = Worker()
self.worker.widget(self.microphone, self.recognizer)
#self.worker.start() #Q Thread method
qt.QThreadPool.globalInstance().start(self.worker)
监听循环确实有效。它拾取音频并很好地解析它。只是每当我对 GUI 做任何事情时,即使按钮不做任何事情,程序也会崩溃。也没有显示错误。任何帮助将不胜感激。我正在为程序 3DSlicer 编写一个 python 模块,因此结构可能看起来略有不同。