大家好!我遇到了语音助手在出现提示时没有响应的问题。但这不是错误,因为它没有显示。
import os
import time
import speech_recognition as sr
from fuzzywuzzy import fuzz
import pyttsx3
import datetime
# settings
opts = {
"alias": ('fox', '', '', '', '', '',
'', '', '', '', ''),
"tbr": ('say', 'tell', 'show', 'how much', 'say'),
"cmds": {
"ctime": ('current time', 'now is the time', 'what time is it'),
"radio": ('turn on the music', 'play the radio', 'turn on the radio'),
"stupid1": ('tell a joke', 'make me laugh', 'you know jokes')
}
}
# the functions
def speak(what):
print(what)
speak_engine.say(what)
speak_engine.runAndWait()
speak_engine.stop()
def callback(recognizer, audio):
try:
voice = recognizer.recognize_google(audio, language="en-EN").lower()
print("[log] Recognized: " + voice)
if voice.startswith(opts["alias"]):
# turn to fox
cmd = voice
for x in opts['alias']:
cmd = cmd.replace(x, "").strip()
for x in opts['tbr']:
cmd = cmd.replace(x, "").strip()
# recognize and execute the command
cmd = recognize_cmd(cmd)
execute_cmd(cmd['cmd'])
except sr.UnknownValueError:
print("[log] Voice not recognized!")
except sr.RequestError as e:
print("[log] Unknown error, check internet!")
def recognize_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':
# say current time
now = datetime.datetime.now()
speak("Now " + str(now.hour) + ":" + str(now.minute))
elif cmd == 'radio':
# play radio
os.system("D:\\Music")
elif cmd == 'stupid1':
# tell a joke
speak("My developer did not teach me jokes ... Ha ha ha")
else:
print('Command not recognized, retry!')
# launch
r = sr.Recognizer()
m = sr.Microphone(device_index=1)
with m as source:
r.adjust_for_ambient_noise(source)
speak_engine = pyttsx3.init()
# Only if you have installed voice for speech synthesis!
voices = speak_engine.getProperty('voices')
speak_engine.setProperty('voice',voices[1].id)
# forced cmd test
speak("My developer did not teach me jokes ...")
# speak("Good afternoon lord")
# speak("Fox is listening")
# stop_listening = r.listen_in_background(m, callback)
# while True: time.sleep(0.1) # infinity loop
有一个错误,你没有从 23 到 26 行的缩进。对于phyton,这很重要。
不正确:
正确:
所有代码中的相同错误。这是您更正的代码:
但要使其正常工作,请删除最后两行之前的 #