kaankutan
kaankutan

Reputation: 89

QThread program is crasing

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_())

If i call this function program is crashing but if i call in debug mode code is working. What's the wrong here? How i should make this code?

Upvotes: 1

Views: 59

Answers (1)

Andrey
Andrey

Reputation: 156

  1. Check if PyAudio is installed
  2. Try to use listen_in_background() not to interrupt Qt Event loop

Worked for me:

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_())

Upvotes: 2

Related Questions