Speech Recognition Python

Viewed 145

I keep getting: NameError: name 'statement' is not defined. It's because i'm not saying anything, and I tried to do an "except" to catch the errors and print something but it still does the error. Here is the code:

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say Anything: ")
        audio = r.listen(source)
        try:
            statement = r.recognize_google(audio).lower()
            print("You said : {}".format(statement))
        except sr.UnknownValueError:
            print(random.choice(command_errors))
        except NameError:
            print(random.choice(command_errors))
        if ai_name in statement:
            engine.say("At your service")
            response_to_wake = ("At your service, " + user_pronoun.lower())
            engine.runAndWait()
            print(response_to_wake)
            Wake = True
        else:
            Wake = False
1 Answers

If recognize_google throws, then statement will not be defined after the try-except block. Consider moving the if ai_name in statement block inside the try block or initialize statement before it.

Related