Search code examples
pythonpython-3.xspeech-recognitionvoice

Python voice assistant


So i wrote this function to get what i say:

def takeCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.pause_threshold = 2
        audio = r.listen(source)
    try:   
        query = r.recognize_google(audio, language='en')

    except Exception as e:
        speak("Say that again please...")
        pass
    
    return query

and then while True the function is running like this:

query = takeCommand().lower()

but i get this error: local variable 'query' referenced before assignment


Solution

  • Your code is running into the exception condition and not defining query try this:

    def takeCommand():
    
        r = sr.Recognizer()
        with sr.Microphone() as source:
            r.pause_threshold = 2
            audio = r.listen(source)
        try:   
            query = r.recognize_google(audio, language='en')
    
        except Exception as e:
            speak("Say that again please...")
            return # NEW CODE
        
        return query