【发布时间】:2021-12-29 14:30:00
【问题描述】:
我正在编写一个虚拟助手,一切都很好,它可以正确收听我的音频输入和响应,但是当我运行程序时,它只需要我的命令一次,程序就结束了。我不知道应该在哪里使用 while 循环,以便程序继续运行,直到我要求它结束。我尝试在不同的函数中添加 while 循环,但似乎都不起作用。
import speech_recognition
import pyttsx3 as tts
import subprocess
import datetime
import webbrowser
import time
now = datetime.datetime.now()
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
x = speaker.getProperty('voices')
speaker.setProperty('voice', x[1].id)
y = speaker.getProperty('rate')
speaker.setProperty('rate' , 175)
def record_audio(ask = False):
with speech_recognition.Microphone() as mic:
if ask:
tts.speak(ask)
print("listening")
recognizer.adjust_for_ambient_noise(mic , 0.05)
audio = recognizer.listen(mic)
try:
voice_data = recognizer.recognize_google(audio , language = "en-IN")
except speech_recognition.UnknownValueError:
tts.speak('Sorry, I did not understand what you just said. Please try again.')
except speech_recognition.RequestError:
tts.speak("Sorry, my speech service is down for the time being. Please try again later.")
return voice_data
def responses(command):
if 'hello' in command:
tts.speak("hello sir, how can I help you.")
elif 'what is your name' in command:
tts.speak("My name is Otto Octavius")
elif 'time' in command:
tts.speak(now.strftime("%I:%M:%S"))
elif 'date' in command:
tts.speak(now.strftime("%Y-%m-%d"))
elif 'open' and 'telegram' in command:
tts.speak("opening telegram")
subprocess.Popen("D:\My Folder\My Softwares\Telegram Desktop\Telegram.exe")
elif 'close' and 'telegram' and 'window' in command:
tts.speak("closing telegram")
subprocess.call(["taskkill","/F","/IM","Telegram.exe"])
elif 'open' and 'binance' in command:
tts.speak("opening binance")
subprocess.Popen("D:\My Folder\My Softwares\Binance\Binance.exe")
elif 'close' and 'binance' in command:
tts.speak('closing binance')
subprocess.call(["taskkill" , "/F" , "IM" , 'Binance.exe'])
elif 'file explorer' in command:
tts.speak("opening file explorer")
webbrowser.open('C:/Users/arfee/Downloads')
elif 'my folder' in command:
tts.speak('opening my folder')
webbrowser.open("D:\My Folder")
elif 'search' in command:
search_object = record_audio("What do you want me to search for?")
url = ("https://www.google.com/search?q=" + search_object)
tts.speak('Searching for ' + search_object)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new_tab(url)
tts.speak("Welcome, how can I help you")
command = record_audio()
responses(command)
【问题讨论】:
标签: python python-3.x