用Python写一个AI语音助手,显示完整代码。
时间: 2024-03-31 09:36:27 浏览: 23
好的,以下是一个简单的Python AI语音助手的完整代码:
```python
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'assistant' in command:
command = command.replace('assistant', '')
print(command)
except:
pass
return command
def run_assistant():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who is' in command:
person = command.replace('who is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_assistant()
```
这个AI语音助手可以通过语音指令来播放YouTube歌曲、查询时间、查询维基百科信息和讲笑话。你可以根据自己的需求进一步扩展它。