问题
I need help. I have followed one of the tutorials. I have got a voice assistant, but it does only one command and than does not do anything. Can you help me to make him listen forever. So, it will always listen, but turn off only, when I close it. PS: Please don't pay attention on other language words. Here is my code:
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)
回答1:
I had to do speak_engine = pyttsx3.init()
not in nearly end of the code, but place it in speak()
来源:https://stackoverflow.com/questions/61073435/doing-voice-assistant-on-python