楼主于最近入手了一块树莓派,想着用它做一些比较有意思的事情。那么,先来做一个语音闹钟好了-先来码一波代码
学习Python中有不明白推荐加入交流群
号:516107834
群里有志同道合的小伙伴,互帮互助,
群里有不错的学习教程!
[Python] 代码
#!/usr/bin/env python
# -*- coding:utf-8
import urllib
import urllib2
import json
import os
WEATHER_CODE = {"00":"晴","01":"多云","02":"阴","03":"阵雨","04":"雷阵雨","05":"雷阵雨伴有冰雹","06":"雨夹雪","07":"小雨","08":"中雨","09":"大雨","10":"暴雨","11":"大暴雨","12":"特大暴雨","13":"阵雪","14":"小雪","15":"中雪","16":"大雪","17":"暴雪","18":"雾","19":"冻雨","20":"沙尘暴","21":"小到中雨","22":"中到大雨","23":"大到暴雨","24":"暴雨到大暴雨","25":"大暴雨到特大暴雨","26":"小到中雪","27":"中到大雪","28":"大到暴雪","29":"浮尘","30":"扬沙","31":"强沙尘暴","53":"霾","99":""}
def get_weather():
url = 'https://weatherapi.market.xiaomi.com/wtr-v3/weather/all?latitude=110&longitude=112&isLocated=true&locationKey=weathercn%3A101270106&days=1&appKey=weather20151024&sign=zUFJoAR2ZVrDy1vF3D07&romVersion=7.2.16&appVersion=87&alpha=false&isGlobal=false&device=cancro&modDevice=&locale=zh_cn'
json_data = urllib2.urlopen(url).read()
parsed_weather = json.loads(json_data)
temperature = parsed_weather['current']['temperature']['value']
humidity = parsed_weather['current']['humidity']['value']
today_forecast = parsed_weather['forecastDaily']['weather']['value'][0]
weather_from = '%02d' % (int(today_forecast['from']))
weather_from = WEATHER_CODE[weather_from]
weather_to = '%02d' % (int(today_forecast['to']))
weather_to = WEATHER_CODE[weather_to]
temperature_from = parsed_weather['forecastDaily']['temperature']['value'][0]['from']
temperature_to = parsed_weather['forecastDaily']['temperature']['value'][0]['to']
#print temperature,humidity
weather_detail = "这里是树莓派天气预报播报台,现在温度{0}度,相对湿度{1}%,今天天气{2}转{3},温度{4}度到{5}度".format(temperature, humidity, weather_from, weather_to, temperature_from, temperature_to)
audio_url = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=mypi&tok=需要从百度申请token&tex=%s&vol=9&per=1' % urllib.quote(weather_detail)
audio_cmd = "mplayer "%s"" % audio_url
os.system(audio_cmd)
return weather_detail
if __name__ == "__main__":
get_weather()
取得天气数据是用的小米的接口,合成语音是使用的百度语音合成接口,系统调用mplayer播放声音即可。
代码编写完毕后,编辑crontab,设定一个时间,每天早上就可以树莓派就会用天气预报叫你起床了。
[Shell] 代码
0 8 * * * /home/pi/SmartHome/Alarm.py
我这里设置的每天8点运行此脚本。
网友评论