Home > database >  Python voice assistant
Python voice assistant

Time:03-24

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

CodePudding user response:

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
  • Related