警告,在看這篇文章之前,你得先去找一個(gè)女朋友,哈哈哈,當(dāng)然沒有的話,也是可以的,而且你也得會(huì)操作系統(tǒng)的安裝,懂些Linux,等你嘗試做出來了,說不定............(期待神評(píng)),也需要一些樹莓派設(shè)備
軟硬件清單
讀卡器以及 SD 卡(裝系統(tǒng)用)
音箱一枚,最好支持 3.5mm
SSH連接工具(SecureCRT,Xshell)
寬帶、路由器(這應(yīng)該是家中常備了)
裝好系統(tǒng)的樹莓派 3B+ 一只(充電器、CPU散熱風(fēng)扇等)
樹莓派 3B+ 的系統(tǒng)默認(rèn)預(yù)裝了 Python3 ,我們只需要安裝一些第三方依賴就可以,以下便是主要代碼:
import time
import random
import os
import pygame
import urllib.request
import json
from aip import AipSpeech
"""
樹莓派打造智能鬧鐘
pip3 install pygame
pip3 install baidu-aip
"""
# 獲取天氣
def get_weather():
# 天氣,編碼,
url = 'http://www.weather.com.cn/data/cityinfo/101120201.html'
obj = urllib.request.urlopen(url)
data_b = obj.read()
data_s = data_b.decode('utf-8')
data_dict = json.loads(data_s)
rt = data_dict['weatherinfo']
weather = '親愛的:該起床了,別睡了,快變小豬了,哈哈哈哈哈,我想你了,你想我嗎?青島的溫度是 {} 到 {},天氣 {}'
weather = weather.format(rt['temp1'], rt['temp2'], rt['weather'])
if '雨' in weather:
weather += '今天別忘記帶雨傘哦!'
du_say(weather)
# 文字轉(zhuǎn)語音
def du_say(weather):
app_id = '****'
api_key = '****'
secret_key = '****'
client = AipSpeech(app_id, api_key, secret_key)
# per 3是漢子 4是妹子,spd 是語速,vol 是音量
result = client.synthesis(weather, 'zh', 1, {
'vol': 5, 'per': 3, 'spd': 4
})
# 識(shí)別正確返回語音二進(jìn)制 錯(cuò)誤則返回dict 參照下面錯(cuò)誤碼
if not isinstance(result, dict):
with open('weather.mp3', 'wb') as f:
f.write(result)
py_game_player('weather.mp3')
# 播放天氣和音樂
def py_game_player(file):
pygame.mixer.init()
print("播報(bào)天氣")
pygame.mixer.music.load(file)
pygame.mixer.music.play(loops=1, start=0.0)
print("播放音樂")
while True:
if pygame.mixer.music.get_busy() == 0:
# Linux 配置定時(shí)任務(wù)要設(shè)置絕對(duì)路徑
mp3 = "/home/pi/alarmClock/"+str(random.randint(1, 6)) + ".mp3"
# mp3 = str(random.randint(1, 6)) + ".mp3"
pygame.mixer.music.load(mp3)
pygame.mixer.music.play(loops=1, start=0.0)
break
while True:
if pygame.mixer.music.get_busy() == 0:
print("播報(bào)完畢,起床啦")
break
if __name__ == '__main__':
get_weather()
#小編整理一套Python資料和PDF,有需要Python學(xué)習(xí)資料可以加學(xué)習(xí)群:766545907,反正閑著也是閑著呢,不如學(xué)點(diǎn)東西啦~~
其實(shí),這款鬧鐘并不智能,并且還有一些昂貴,幸好身邊有兩個(gè)平時(shí)不怎么用的音箱,就拿來廢物利用了。好處是可以隨心所欲的DIY,比如做一款A(yù)PP,或者后臺(tái)管理,進(jìn)行遠(yuǎn)程控制,給予女朋友無時(shí)無刻的關(guān)懷。