我正在编写python代码(提供); 但是当我说“打开照片”时,一切正常,它认识到我说了“打开照片”,但抛出了声明以外的内容,而不是“ elif listen()==“打开照片”:输出”。
import speech_recognition as sr
import pyttsx3
import time
friday = pyttsx3.init('sapi5')
r = sr.Recognizer()
mic = sr.Microphone()
friday.setProperty('rate', 150)
def listen():
with mic as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(text)
return text
except sr.UnknownValueError:
friday.say("sorry sir , could't do that")
friday.runAndWait()
print("started!")
while 1:
if listen() == "hello Jarvis":
friday.say("hello sir")
friday.runAndWait()
elif listen() == "open photos":
friday.say("opening")
friday.runAndWait()
答案 0 :(得分:0)
我认为您需要的是更好的关注。 listen
将消耗输入;再次调用它会迫使您重复该短语。相反,请在第一时间注意。 :-)
heard = listen()
if heard == "hello Jarvis":
friday.say("hello sir")
friday.runAndWait()
elif heard == "open photos":
friday.say("opening")
friday.runAndWait()
请注意,如果您一致地缩进,则代码更易于阅读:即使在独立的块之间,相同处理级别的代码也应缩进同一级别。