【发布时间】:2019-09-19 00:10:39
【问题描述】:
是否可以使用 python 中的语音识别根据从用户收到的输入调用函数?我的意思是,如果用户说出像“add”这样的词,那么基于该输入调用 add() 函数。有可能吗?
我已经编辑并添加了我的完整代码。它正确理解我的输入,打印出来,然后在不调用特定函数的情况下再次开始监听。所以现在任何人都可以向我推荐我该怎么做?
import pyttsx3
import datetime
import speech_recognition as sr
import os
import sys
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishme():
hour = int(datetime.datetime.now().hour)
if hour >= 0 & hour < 12:
speak("Good Morning!")
elif hour>=12 and hour<18:
speak("Good Afternoon!")
else:
speak("Good Afternoon!")
speak("I am an AI Sir. Please tell me how may I help you")
def takecommand():
# It takes microphone input from user
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening....")
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
try:
print("Recognizing....")
query = r.recognize_google(audio, language = 'en-IN')
print(f'User said: {query}\n')
except Exception as e:
print(e)
print("Say that again please.....")
speak("Say that again please")
return "None"
return query
def add(num1, num2):
c = num1 + num2
print(c)
def subs(num1, num2):
d = num1 - num2
print(d)
def multiply(num1, num2):
e = num1 * num2
print(e)
def divide(num1, num2):
f = num1 / num2
print(f)
if __name__ == '__main__':
wishme()
while True:
query = takecommand().lower()
if 'add' in query:
add(2, 5)
if 'substract' in query:
subs(2, 5)
if 'multiply' in query:
multiply(2, 5)
elif 'exit' in query:
sys.exit()
【问题讨论】:
-
是的,有可能。
-
我该怎么办?可以请我介绍一下吗?
-
您的代码似乎正是这样做的。
-
但它没有调用该函数。什么都没有发生
-
@Galrikh 欢迎来到 SO。您可能想阅读How to Ask 和minimal reproducible example 并相应地编辑您的问题(好吧,如果您希望得到一些认真的帮助,我的意思是......)。哦,是的; 修复代码缩进 - Python 使用缩进作为语法的一部分,因此缩进严重的代码毫无意义。
标签: python python-3.x speech-recognition text-to-speech