Noam Kramer
Noam Kramer

Reputation: 93

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

Upvotes: 1

Views: 134

Answers (1)

James Burgess
James Burgess

Reputation: 497

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

Upvotes: 1

Related Questions