前提条件
- 安装以下Python库:
speech_recognition
(语音识别)pyttsx3
(文本转语音)requests
(用于查询天气API)datetime
(获取当前时间)wikipedia
(查询维基百科)
可以通过以下命令安装这些库:
pip install speechrecognition pyttsx3 requests wikipedia
代码实现
import speech_recognition as sr
import pyttsx3
import datetime
import requests
import wikipedia
# 初始化文本到语音引擎
engine = pyttsx3.init()
# 设置语音引擎的语音属性(可选)
engine.setProperty('rate', 150) # 设置语速
engine.setProperty('volume', 1) # 设置音量(0.0到1.0之间)
# 定义语音助手功能
def speak(text):
"""将文本转换为语音输出"""
engine.say(text)
engine.runAndWait()
def listen():
"""通过麦克风监听用户的语音并转换为文本"""
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source) # 调整环境噪声
audio = recognizer.listen(source)
try:
print("Recognizing...")
query = recognizer.recognize_google(audio)
print(f"You said: {query}")
return query.lower()
except sr.UnknownValueError:
speak("Sorry, I could not understand your speech. Please try again.")
return None
except sr.RequestError:
speak("Sorry, I am unable to connect to the service. Please check your internet.")
return None
def get_weather(city):
"""获取天气信息"""
api_key = "your_api_key" # 需要申请OpenWeatherMap API密钥
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city}&appid={api_key}&units=metric"
response = requests.get(complete_url)
data = response.json()
if data["cod"] == "404":
speak("Sorry, I couldn't find the weather details for that city.")
else:
main = data["main"]
weather_description = data["weather"][0]["description"]
temperature = main["temp"]
speak(f"The weather in {city} is currently {weather_description} with a temperature of {temperature} degrees Celsius.")
def get_time():
"""获取当前时间"""
now = datetime.datetime.now()
time_str = now.strftime("%H:%M")
speak(f"The current time is {time_str}.")
def search_wikipedia(query):
"""查询维基百科"""
try:
result = wikipedia.summary(query, sentences=2)
speak(result)
except wikipedia.exceptions.DisambiguationError as e:
speak("There are multiple results. Please be more specific.")
except wikipedia.exceptions.HTTPTimeoutError:
speak("I couldn't connect to Wikipedia. Please try again later.")
# 主函数,启动语音助手
def run_assistant():
speak("Hello, how can I assist you today?")
while True:
query = listen()
if query is None:
continue
if "time" in query:
get_time()
elif "weather" in query:
speak("Which city do you want to know the weather of?")
city = listen()
if city:
get_weather(city)
elif "search" in query or "wikipedia" in query:
speak("What would you like to search on Wikipedia?")
search_query = listen()
if search_query:
search_wikipedia(search_query)
elif "exit" in query or "quit" in query:
speak("Goodbye! Have a nice day!")
break
else:
speak("Sorry, I didn't understand that. Please try again.")
# 启动语音助手
if __name__ == "__main__":
run_assistant()