Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

python - ' UnboundLocalError: local variable 'command' referenced before assignment '

Here is the code. I am making a microphone class that recognize user voice. It gives me an UnboundLocalError. That happens when I add a return command to the mic_config() method.

    import speech_recognition as sr
    import pyaudio
    from speaker import Speaker


    class Microphone: 
       """Microphone class that represent mic and get user's voice..."""

        def __init__(self):
            """Initializing of class"""
            self.recognizer = sr.Recognizer()  # Voice recognizer
            self.microphone = sr.Microphone()  # Mic

        def mic_config(self):

            try:
               with self.microphone as source:  # Getting mic
               print('Listening...')
               voice = self.recognizer.listen(source)
               command = self.recognizer.recognize_google(voice, language='en-IN')  # Using google api
               print(command)  # Printing what user said

            except:  # Expecting errors
                  pass
            return command


     m1 = Microphone()  # just a test
     m1.mic_config()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yeah as Carcigenicate said it is because command is only defined in the try block. This means that if there is an error then command is not defined. I don't know if it is just in the code you posted here but there is an indent error in the with statement

try:
    with self.microphone as source:
        print('Listening...')
        voice = self.recognizer.listen(source)
        command = self.recognizer.recognize_google(voice, language='en-IN')
        print(command)

except: 
    raise CustomError
    # or return None, command = None, etc just define command before the last line
    # or don't let the function reach the return command statement

return command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...