0

我想線程一個speech_recognition函數在後臺連續運行,並檢查音頻函數,看看有什麼文字說話,並採取相應的行動,我試着線程2功能運行平行但語音偵察功能一遍又一遍地被調用,我從來沒有使用線程,並在YouTube上跟隨一個教程來線程我的功能,我得到,我可以犯了一個非常愚蠢的錯誤,所以我請求誰回答這個問題在他們的答案和我的錯誤中有點詳細。謝謝。類型錯誤函數缺少一個參數'self'

編輯
所以我刪除其造成這個錯誤使得整個程序冗餘我的聽力功能的while循環,但現在我得到類型錯誤:checkingAudio()失蹤1個人需要的位置參數:「自我」,我 as explained here要求我實例化一個類,但我做到了這一點,同樣的錯誤仍然存​​在。

class listen(threading.Thread): 

    def __init__(self): 

     self.playmusicobject = playmusic() 
     self.r = sr.Recognizer() 

     self.listening() 

def listening(self): 

    self.objectspeak = speak() 
    self.apiobject = googleAPI() 
    print("say something") 
    time.sleep(2.0) 
    with sr.Microphone() as source: 
     # self.objectspeak.speaking("say something") 
     self.audio = self.r.listen(source) 


    def checkingAudio(self): 
     time.sleep(0.5) 

     try: 
      a = str(self.r.recognize_google(self.audio)) 
      a = str(self.r.recognize_google(self.audio)) 
      print(a) 

      if a in greetings: 
       self.objectspeak.speaking("I am good how are you?") 

      if a in music: 
       print("playing music") 
       self.playmusicobject.play() 
      if a in stop: 
       print("stopping") 
       self.playmusicobject.b() 

      if a in api: 
       self.apiobject.distance() 

      else: 
       print("error") 

     except sr.UnknownValueError: 
      print("Google Speech Recognition could not understand audio") 

     except sr.RequestError as e: 
      print("Could not request results from Google Speech Recognition service; {0}".format(e)) 


class speak: 
    THIS IS A PYTTS class 




class googleAPI: 
    GOOGLE DISTANCE API function calculates distance between 2 places 

class playmusic: 

    def play(self): 
     self.objectspeak = speak() 
     playsound.playsound('C:\\Users\legion\Downloads\Music\merimeri.mp3') 

    def b(self): 
     self.objectspeak.speaking("music stopped") 

while 1: 
    a = listen 
    t1 = threading.Thread(target=listen()) 
    t2 = threading.Thread(target= a.checkingAudio()) 
    t1.join() 
    t2.join() 
+1

在回答您的編輯,你沒有實例化'listen'。你忘了父親;你想'a = listen()'。但是,當然,現在你正在執行你想要在線程之外進行線程工作,並且仍然無法在線程中進行任何工作(因爲在定義目標時你不想要這些工作)。閱讀我的答案,它涵蓋了所有這些。 – ShadowRanger

回答

3

你實際上並沒有使用任何線程,你在你的主線程調用的函數,而不是使他們的目標由線程調用。即使你有,你從來沒有打電話start開始執行線程。你需要修正幾件事:

首先,確保你只執行初始化,但不是正在進行的工作,在__init__;您需要首先完成創建對象,即使可以使用checkingAudio也可以使用該對象。

其次,你的線程創建更改爲:

while 1: 
    listener = listen() # Make the object 
    t1 = threading.Thread(target=listener.listening) # Note: No parens or we invoke in main thread 
    t2 = threading.Thread(target=listener.checkingAudio) # Note: No parens 
    t1.start() # Actually launch threads 
    t2.start() 
    t1.join() 
    t2.join() 
+0

謝謝你的回答和解釋。我很感謝@ ShadowRanger –