[英]' UnboundLocalError: local variable 'command' referenced before assignment '
I am making a microphone class that recognize user voice.我正在制作一个可以识别用户语音的麦克风 class。 It gives me an UnboundLocalError
.它给了我一个UnboundLocalError
。 That happens when I add a return command
to the mic_config()
method.当我向mic_config()
方法添加return command
时,就会发生这种情况。
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)
except:
pass
return command
m1 = Microphone() # just a test
m1.mic_config()```
Yeah as Carcigenicate said it is because command is only defined in the try block.是的,正如 Carcigenicate 所说,这是因为命令仅在 try 块中定义。 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我不知道它是否只是在您在此处发布的代码中,但 with 语句中存在缩进错误
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.