用Python写一个AI语音助手,显示完整代码。
时间: 2024-03-31 09:36:53 浏览: 163
whisper-一个使用python快速实现合成语音的库,离线人工智能合成,无需联网
5星 · 资源好评率100%
好的,以下是一个简单的Python AI语音助手的完整代码,它可以执行一些基本的任务,如回答问题、播放音乐等:
```python
import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import random
import pywhatkit as kit
# 初始化语音引擎
engine = pyttsx3.init()
# 设置语音助手的声音
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
# 定义说话的函数
def speak(audio):
engine.say(audio)
engine.runAndWait()
# 定义欢迎函数
def welcome():
hour = datetime.datetime.now().hour
if hour >= 0 and hour < 12:
speak("早上好!")
elif hour >= 12 and hour < 18:
speak("下午好!")
else:
speak("晚上好!")
speak("我是你的AI语音助手,有什么我可以帮你的吗?")
# 定义听函数
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language="zh-CN")
print(f"You said: {query}\n")
except Exception as e:
print(e)
print("Say that again please...")
return "None"
return query
# 主函数
if __name__ == "__main__":
welcome()
while True:
query = takeCommand().lower()
# 执行命令
if "wikipedia" in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak("According to Wikipedia")
speak(results)
elif "open youtube" in query:
webbrowser.open("youtube.com")
elif "open google" in query:
webbrowser.open("google.com")
elif "play music" in query:
music_dir = "D:\\Music\\English"
songs = os.listdir(music_dir)
print(songs)
random_song = random.choice(songs)
os.startfile(os.path.join(music_dir, random_song))
elif "what's the time" in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"现在的时间是{strTime}")
elif "send message" in query:
kit.sendwhatmsg("+919876543210", "你好", 20, 30)
elif "bye" in query:
speak("再见,祝你有愉快的一天!")
exit()
```
这个简单的AI语音助手可以执行一些基本任务,如搜索维基百科、打开网站、播放音乐、显示当前时间、发送WhatsApp消息等。您可以根据您的需求对其进行修改和扩展。
阅读全文