前言

最近好久没有碰我的树莓派了,有吃灰的趋势,赶紧拿出来折腾一波,首先树莓派是没有喇叭的,你需要外接一个喇叭,我是直接用的一个小音响(usb供电,3.5mm插头)连接的,效果还不错。小音箱的功率最好不要超过3W,不然树莓派可能带不起来,我的机器型号是树莓派3B+。

安装setuptools

到网上下载 setuptools-41.0.1.zip ,解压,进行编译安装

unzip setuptools-41.0.1.zip
cd setuptools-41.0.1
sudo setup.py build
sudo setup.py install

安装pip

sudo apt install python-pip
sudo pip install --upgrade pip

安装beautifulsoup4

重要!这个在编写 python 程序时用来处理爬取到的网页信息

sudo pip3 install beautifulsoup4

安装百度语音合成jdk

到百度官网下载 python 版本的语音合成jdk文件 aip-python-sdk-2.2.15.zip

注意,语音合成和语言识别是用一个压缩包

unzip aip-python-sdk-2.2.15.zip
cd aip-python-sdk-2.2.15
sudo python3 setup.py install

注意,因为我用的 python3 来运行的脚本,所以安装 beautifulsoup4 和语音合成jdk都是用 python3 来安装

安装mplayer

安装mplayer音乐播放器,用来播放音频文件

sudo apt-get install mplayer

程序代码

#coding:utf-8
from urllib.request import urlopen
from bs4 import BeautifulSoup
from aip import AipSpeech
import os

# 获取获取墨迹天气,把链接换成你所在城市的那个页面就行
url = urlopen('https://tianqi.moji.com/weather/china/guizhou/guiyang')
soup = BeautifulSoup(url, 'html.parser')   # parser解析
alert = soup.find('div', class_="wea_alert clearfix")

# 空气质量
# print(alert.em.string)
weather = soup.find('div', class_="wea_weather clearfix")

# 当前温度
# print(weather.em.string)

# 天气
# print(weather.b.string)
humidity = soup.find('div',class_='wea_about clearfix')

# 湿度
# print(humidity.span.string)

# 风向
# print(humidity.em.string)

tips = soup.find('div',class_='wea_tips clearfix')

# 今日天气提示
# print(tips.em.string)

# 创建weather_text接收天气的总体信息
weather_text = "空气质量:" + alert.em.string + ",当前温度:" + weather.em.string + " 摄氏度" + ",天气:" + weather.b.string + ','+ humidity.span.string + ',风向:'+ humidity.em.string + ",今日天气提示:"+ tips.em.string

# 这里填写你在百度那儿申请到的信息
APP_ID = '申请到的APP_ID'
API_KEY = '申请到的API_KEY'
SECRET_KEY='申请到的SECRET_KEY'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 将天气信息传给语音合成api
result = client.synthesis(text = weather_text, options={'vol':5})

# 保存服务器返回的mp3文件,然后调用mplayer播放
if not isinstance(result,dict):
    with open('weather.mp3','wb') as f:
        f.write(result)
    audio_cmd = "mplayer weather.mp3"
    os.system(audio_cmd);
else:print(result)

定时任务

程序写好了,保存为 weather.py ,然后将其加入定时任务,我这里定为每天早上8点运行该程序,这样,每天早上8点,树莓派都会进行天气播报。

crontab -e
0 8 * * * python3 /home/pi/weather.py

总结

我这个程序是解析的墨迹天气的网页数据,要程序爬取网页然后再获取指定数据,最后再合成,速度略慢。直接调用天气api速度应该会快不少,这里我就不弄了。

分类: LinuxOther 标签: 树莓派Linux

评论

暂无评论数据

暂无评论数据

目录