Thread SpeechRecognition and get return value while doing other stuff at the same time

Viewed 431

My question is how to thread a function that needs time to execute , then return a value , whilst I can do other stuff at the same time.

I saw others similar questions and solutions but I don't get how to apply them here.

import speech_recognition as sr
r = sr.Recognizer()

import threading
from queue import Queue

queue = Queue()

def mySpeechRecognizer():

    print("START SPEECH INPUT\n") #

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
            
        try:
            audio = r.listen(source)#, timeout = 5)  #####
            userInput = r.recognize_google(audio)
                
            if any(userInput) == True:
                print("Text Input :", userInput) #

                # do sth here
                
                print("END SPEECH INPUT NORMAL") #

                return userInput #
                    
        except Exception as e:
            print("Exception In Function mySpeechRecognizer() :", e)
                    
            print("END SPEECH INPUT EXCEPTION") #

            return #

recognize = threading.Thread(target = lambda q: q.put(mySpeechRecognizer()), args = (queue, ))
recognize.start()

print('do sth')

recognize.join()

print('do sth')

print(queue.get())

print('do sth')

My expectation is that it will print 3 times "do sth" while recognizing. Once it finishes , it will print the return value without blocking the print , i.e. getting queue.get() while print

How can I accomplish this , and what's wrong with my attempt ?

1 Answers

I think I have finally came up with a solution . . .

We can use queue.empty() to check whether the func has a return value or not ( True --> is empty i.e. no return val ; False --> not empty i.e. has return val ) so when queue.empty() remains True , I can do other stuff like print. With the while loop , it will be something like this :

...

while queue.empty():    # don't have return val
    print("do sth")     # do stuff

else:                   # --> have return val
    print(queue.get())  # print the return val of the func
    recognize.join()    # join the thread

Correct me if I am wrong ?

Related