我需要帮助。我遵循了其中一个教程。我有一个语音助手,但它只执行一个命令,而不做任何事情。你能帮我让他永远听下去吗?所以,它会一直听,但只有在我关闭它时才会关闭。PS:请不要关注其他语言单词。这是我的代码:
import pyttsx3
import os
import time
from fuzzywuzzy import fuzz
import datetime
import speech_recognition as sr
opts = {
"alias": ("петя", "петечка", "петюлечка", "петрович", "петич", "петр", "петька", "петь"),
"tbr": ("скажи", "расскажи", "покажи", "сколько", "произнеси"),
"cmds": {
"ctime": ("текущее время", "сейчас времени", "который час"),
"radio": ("включи музыку", "воспроизведи радио", "включи радио"),
"stupid1": ("расскажи анекдот")
}
}
def speak(what):
print(what)
speak_engine.say(what)
speak_engine.runAndWait()
speak_engine.stop()
def callback(recongizer, audio):
try:
voice = recongizer.recognize_google(audio, language="ru-RU").lower()
print("[log] Распознано: " + voice)
if voice.startswith(opts["alias"]):
cmd = voice
for x in opts['alias']:
cmd = cmd.replace(x, "").strip()
for x in opts['tbr']:
cmd = cmd.replace(x, "").strip()
cmd = recongize_cmd(cmd)
execute_cmd(cmd['cmd'])
except sr.UnknownValueError:
print("[log] Голос не распознан!")
except sr.RequestError as e:
print("[log] Неизвестная ошибка, проверьте интернет")
def recongize_cmd(cmd):
RC = {'cmd': '', "percent": 0}
for c, v in opts['cmds'].items():
for x in v:
vrt = fuzz.ratio(cmd, x)
if vrt > RC['percent']:
RC['cmd'] = c
RC['percent'] = vrt
return RC
def execute_cmd(cmd):
if cmd == 'ctime':
now = datetime.datetime.now()
speak("Сейчас " + str(now.hour) + ":" + str(now.minute))
elif cmd == 'radio':
# воспроизвести радио
os.system("D:\\Jarvis\\res\\radio_record.m3u")
elif cmd == 'stupid1':
speak("Мой разработчик не научил меня анекдотам ... Ха ха ха")
else:
print('Команда не распознана, повторите!')
r = sr.Recognizer()
m = sr.Microphone(device_index=1)
with m as sourse:
r.adjust_for_ambient_noise(sourse)
speak_engine = pyttsx3.init()
speak("Привет")
speak("Петя слушает")
stop_listening = r.listen_in_background(m, callback)
while True: time.sleep(0.1)