一、天气预报数据
首先需要将天气数据取到,网上很多网站都提供免费的数据,这里以和风天气为例。
5 | json_data = json.loads(res.text) |
6 | tomorrow = json_data[ 'HeWeather6' ][0][ 'daily_forecast' ][0] |
7 | weather_day = tomorrow[ 'cond_txt_d' ] |
8 | weather_night = tomorrow[ 'cond_txt_n' ] |
9 | tmp_high = tomorrow[ 'tmp_max' ] |
10 | tmp_low = tomorrow[ 'tmp_min' ] |
11 | wind_dir = tomorrow[ 'wind_dir' ] |
12 | wind_sc = tomorrow[ 'wind_sc' ] |
13 | weather_forcast_txt = "下面是天气预报时间,东莞明天白天天气%s,夜间天气%s,最高气温%s摄氏度,最低气温%s摄氏度,风力%s,风向%s。" %(weather_day,weather_night,tmp_high,tmp_low,wind_sc,wind_dir) |
14 | print (weather_forcast_txt) |
测试结果如下:

二、百度语音合成
首先在百度语音里创建一个应用,这时可以得到API Key、Secret Key。然后再访问:
https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=你的api key&client_secret=你的secret key
这个网址,可以得到access_token。
然后再将token放到下面的网址,就可以了。
备注说明一下:其实“cuid=设备mac地址或手机的IMEI码”这里保留原样即可,不用填写也照常可以工作。
三、树莓派的配置
加上以下两行代码即可。
当然,前提是我的树莓派已经安装了mp3播放软件mpg123,如果你的树莓派没有安装的话,需要先用“sudo apt-get install mpg123”命令安装。
3 | os.system( 'mpg123 "%s"' %(url)) |
再在crontab中加入
1 | 20 30 * * * python3 /home/pi/...(你的天气播报脚本的路径) |
表示20:30,自动进行天气预报的语音播报。
四、附上最终的代码:
6 | json_data = json.loads(res.text) |
7 | tomorrow = json_data[ 'HeWeather6' ][0][ 'daily_forecast' ][0] |
8 | weather_day = tomorrow[ 'cond_txt_d' ] |
9 | weather_night = tomorrow[ 'cond_txt_n' ] |
10 | tmp_high = tomorrow[ 'tmp_max' ] |
11 | tmp_low = tomorrow[ 'tmp_min' ] |
12 | wind_dir = tomorrow[ 'wind_dir' ] |
13 | wind_sc = tomorrow[ 'wind_sc' ] |
14 | weather_forcast_txt = "下面是天气预报时间,东莞明天白天天气%s,夜间天气%s,最高气温%s摄氏度,最低气温%s摄氏度,风力%s级,风向%s。" %(weather_day,weather_night,tmp_high,tmp_low,wind_sc,wind_dir) |
16 | os.system( 'mpg123 "%s"' %(url)) |
最后再说一下,百度语音合成token只有一个月有效期,所以一个月之后,需要重新生成一下token。
另外,百度语音合成的地址改了,以前是有一个网页版的,不过以后只能用上面的代码方式来实现了。
其中 per=0是用来定义男声、女生的,spd=5表示语速。