问题描述
你好 stachoverflow 社区, 我刚刚开始编程,我的第一个项目是一个小的虚拟助手。我从 yt 视频中获得了一些灵感和支持。无论如何,出现了一些问题:当我在 Pycharm 中启动程序并且没有给出命令(我对 alexa 这个词什么也没说)时,程序在 arounf 12 秒后崩溃。我认为这与循环有关,因为我尝试用语音命令打破循环,我的下一个问题是什么。我尝试了一些事情来用语音命令结束循环内的循环,但它不起作用。这甚至可能吗?你们有其他解决方案吗? 这是错误: 回溯(最近一次调用最后一次): 文件“C:\Users”,第 54 行,在 run_alexa() 文件“C:\Users”,第 28 行,在 run_alexa 中 命令 = take_command() 文件“C:\Users”,第 26 行,在 take_command 中 返回命令 UnboundLocalError:赋值前引用了局部变量“command”
先谢谢你! 阿德里安 (我的代码)我希望你能帮助我! [https://i.stack.imgur.com/m8Neo.png][1] [https://i.stack.imgur.com/qNTdG.png][2]
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice",voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print("listening...")
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if "alexa" in command:
command = command.replace("alexa","")
# print(command)
except:
pass
return command
def run_alexa():
command = take_command()
print(command)
if "play" in command:
song = command.replace("play","")
talk("playing" + song)
pywhatkit.playonyt(song)
elif "time" in command:
time = datetime.datetime.Now().strftime("%H:%M")
talk("The current time is " + time)
print(time)
elif "who is" in command:
person = command.replace("who is","")
info = wikipedia.summary(person,1) # how many lines do I want in the summary
print(info)
talk(info)
elif "tell me a joke" in command:
talk(pyjokes.get_joke())
elif "stock" in command:
stock_price = pywhatkit.search(command)
talk(stock_price)
elif "stop" in command:
talk("alexa is going down")
else:
talk("Please say the command again.")
while True:
run_alexa()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)