Python 天气查询到实现语音播放

时间:2022-07-11 14:01:09
import requests        #引用requests模块
import pygame # 获取天气
def inquery(self):
url = "https://free-api.heweather.com/v5/now?city={0}".format(self)+"&key=2d849c62d67a4b9e94607d0f1c744561"
# url = "https://free-api.heweather.com/v5/now?city=钦州&key=2d849c62d67a4b9e94607d0f1c744561"
respone = requests.get(url=url)
deal(respone.json()) # 数据处理
def deal(self): data = self['HeWeather5'][0]['basic']['city']+'实时天气:'+self['HeWeather5'][0]['now']['cond']['txt']+',温度:'+self['HeWeather5'][0]['now']['tmp']+',相对湿度:'+self['HeWeather5'][0]['now']['hum']+','+self['HeWeather5'][0]['now']['wind']['dir']+self['HeWeather5'][0]['now']['wind']['sc']+'级。'
# 获取城市
print(data)
print(self['HeWeather5'][0]['basic']['city']) # 获取天气状况
print(self['HeWeather5'][0]['now']['cond']['txt']) # 相对湿度
print(self['HeWeather5'][0]['now']['hum']) # 温度
print(self['HeWeather5'][0]['now']['tmp']) # 风级
print(self['HeWeather5'][0]['now']['wind']['dir'])
print(self['HeWeather5'][0]['now']['wind']['sc'])
voice(data) # 音频处理(这里调用的是百度语音的接口,官网有使用教程,很简单~)
def voice(data):
from aip import AipSpeech """ 你的 APPID AK SK """
APP_ID = '你的 App ID' API_KEY = '你的 Api Key' SECRET_KEY = '你的 Secret Key client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) result = client.synthesis(data, 'zh', 1, {
'vol': 5,
}) # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as f:
f.write(result)
play() # 播放音频
def play():
import time
import pygame
file = r'auido.mp3'
pygame.mixer.init()
print("播放天气:")
track = pygame.mixer.music.load(file) pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.music.stop() if __name__ == '__main__':
print("天气查询系统:")
city = input("请输入要查询的城市>>>: ")
inquery(city)