QThread程序正在崩溃

2024-06-16 09:56:53 发布

您现在位置:Python中文网/ 问答频道 /正文

class textProssesThread(QThread):
   def __init__(self,audio):
       super().__init__()
       self.audio = audio
   def run(self):
       text = r.recognize_google(self.audio)
       mainWin.pybutton.setText(text)

class listenThread(QThread):
   def __init__(self):
       super().__init__()
   def run(self) -> None:
       with sr.Microphone() as source:
           audio = r.listen(source)
           a = textProssesThread(audio)
           a.start()

class MainWindow(QMainWindow):
   def __init__(self):
       QMainWindow.__init__(self)
       self.pybutton = QPushButton('Click me', self)
       self.pybutton.clicked.connect(self.clickMethod)
       self.pybutton.resize(100, 32)
       self.pybutton.move(50, 50)
       self.show()
    def clickMethod(self):
       a = listenThread()
       a.start()

if __name__ == "__main__":
   app = QApplication(sys.argv)
   mainWin = MainWindow()
   sys.exit(app.exec_())

若我调用此函数,程序将崩溃,但若我在调试模式下调用,代码将正常工作。这里怎么了?我应该如何制作这个代码


Tags: runtextselfsourceinitdefstartaudio
1条回答
网友
1楼 · 发布于 2024-06-16 09:56:53
  1. 检查是否安装了PyAudio
  2. 尝试在_background()中使用listen_不中断Qt事件循环

为我工作:

import sys

from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
import speech_recognition as sr



class listenThread(QThread):
   def __init__(self):
       super().__init__()
       self.r = sr.Recognizer()
       self.mic = sr.Microphone()

   def run(self) -> None:
        self.r.listen_in_background(self.mic, self.recognize)
        self.sleep(4)

   def recognize(self, recognizer, audio):
       try:
        text = recognizer.recognize_google(audio)
        mainWin.pybutton.setText(text)
       except Exception as exc:
           print(exc)


class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.pybutton = QPushButton('Click me', self)
        self.pybutton.clicked.connect(self.clickMethod)
        self.pybutton.resize(100, 32)
        self.pybutton.move(50, 50)
        self.show()

    def clickMethod(self):
        a = listenThread()
        a.start()


if __name__ == "__main__":
   app = QApplication(sys.argv)
   mainWin = MainWindow()
   sys.exit(app.exec_())

相关问题 更多 >