用python写一个Ai语音助手小程序,显示代码
时间: 2023-06-17 18:05:43 浏览: 195
计算机语音表达代码小程序
下是一个简单的Python语音助手小程序示例,它使用SpeechRecognition库和pyttsx3库来识别和生成语音:
```python
import speech_recognition as sr
import pyttsx3
# initialize speech recognition engine
r = sr.Recognizer()
# initialize text-to-speech engine
engine = pyttsx3.init()
# obtain audio from the microphone
with sr.Microphone() as source:
print("Speak:")
audio = r.listen(source)
# recognize speech using Google Speech Recognition
try:
print("You said: " + r.recognize_google(audio))
engine.say("You said: " + r.recognize_google(audio))
engine.runAndWait()
except sr.UnknownValueError:
print("Could not understand audio")
engine.say("Sorry, I could not understand what you said.")
engine.runAndWait()
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
engine.say("Sorry, there was an error in processing your request.")
engine.runAndWait()
```
这个程序会启动麦克风,等待用户输入语音。一旦用户说话,程序会使用Google Speech Recognition API将语音转换为文本,并将其打印到屏幕上。同时,使用pyttsx3库,程序还会将文本转换为语音,然后将其播放出来。
阅读全文