# 录下来你讲的话 defrecordAudio(): # 用麦克风记录下你的话 print("开始麦克风记录下你的话") r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) data = "" try: data = r.recognize_google(audio) print("You said: " + data) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) return data
if __name__ == '__main__': time.sleep(2) whileTrue: data = recordAudio() print(data)
下面是我乱说的英语
对话
上面,我们实现了用麦克风记录下你的话,并且得到了对应的文本,那么下一步就是字符串的文本操作了,比如说how are you,那回答"I am fine”,然后将"I am fine”通过gtts是将文字转化为语音
# @Author:Runsen # -*- coding: UTF-8 -*- import speech_recognition as sr from time import ctime import time import os from gtts import gTTS
# 录下来你讲的话 def recordAudio(): # 用麦克风记录下你的话 r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source)
data = "" try: data = r.recognize_google(audio) print("You said: " + data) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
return data
# 自带的对话技能(逻辑代码:rules) def jarvis(): while True: data = recordAudio() print(data) if "how are you" in data: speak("I am fine") if "time" in data: speak(ctime()) if "where is" in data: data = data.split(" ") location = data[2] speak("Hold on Runsen, I will show you where " + location + " is.") # 打开谷歌地址 os.system("open -a Safari https://www.google.com/maps/place/" + location + "/&")
if "bye" in data: speak("bye bye") break
if __name__ == '__main__': # 初始化 time.sleep(2) speak("Hi Runsen, what can I do for you?")
# 跑起 jarvis()
当我说how are you?会弹出I am fine的mp3
当我说where is Chiana?会弹出Hold on Runsen, I will show you where China is.的MP3