所以虚拟助手可以工作,但是当我说一些东西时,它不会听或响应
listening...
recognizing...
network connection issue...
它一直在打印此内容☝
这是我编写的代码
import speech_recognition as sr
import wikipedia
import datetime
import pyttsx3
import webbrowser
import random
import os
import pyaudio
#text to speech
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices)
#print(voices)
engine.setProperty('voice',voices[0].id)
def speak(audio): #here audio is var which contain text
engine.say(audio)
engine.runAndWait()
def wish():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour < 12:
speak("good morning, i am your virtual assistant")
elif hour >= 12 and hour < 18:
speak("good afternoon, i am your virtual assistant")
else:
speak("hello, i am your virtual assistant")
#now convert audio to text
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("recognizing...")
speak("recognising")
query = r.recognition_google(audio, language='en-in')
print(f"user said:{query}\n")
except Exception:
speak("error...")
print("network connection issue...") #for error handling
return "none"
return query
#for the main function
if __name__ == "__main__":
wish()
while True:
query = takeCommand().lower()
if "wikipedia" in query:
speak("searching details...")
query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences = 2)
print(results)
speak(results)
elif "open youtube" in query or "youtube" in query:
speak("opening youtube")
webbrowser.open("www.youtube.com")
elif "open google" in query or "google" in query:
speak("opening google")
webbrowser.open("www.google.co.in")
elif "music from laptop" in query or "music" in query:
speak("ok playing music")
music_dir = "./music"
musics = os.listdir(music.dir)
os.startfile(os.path.join(music_dir, music[0]))
elif "music from laptop" in query or "music" in query:
speak("ok playing music")
music_dir = "./video"
musics = os.listdir(music.dir)
os.startfile(os.path.join(music_dir, video[0]))
elif "good bye" in query:
speak("good bye")
exit()
elif "shutdown" in query:
speak("shutting down")
os.system('shutdown -s')
因此,运行后它说它需要的东西也会打印它需要的东西,但是当要听用户说的东西时,它只是没有回应,而是继续打印 听... 认识... 网络连接问题...
答案 0 :(得分:0)
您的代码似乎是正确的!我猜函数speak()中存在缩进错误。
您是否尝试在连接互联网时说出命令?
答案 1 :(得分:0)
speak()
函数中存在缩进错误。takeCommand()
函数中,它应该是r.recognize_google
而不是r.recognition_google
。编辑:
我从未尝试过,所以我不知道。
添加:
elif "search on google" in query:
speak("searching on google")
line = query.strip("search on google ")
webbrowser.open("www.google.co.in"+"/search?q="+line)
并确保在打开的Google Elif中删除or "google" in query
或使用以下方法更改整个内容:
elif "google" in query and "search" not in query:
speak("opening google")
webbrowser.open("www.google.co.in")