「玩轉樹莓派」爲女友打造一款智能語音鬧鐘

前言

最近在作智慧工廠相關的工做,多多少少了解了一點物聯網相關的技術。因而心血來潮,尋思本身能夠作點什麼,恰巧以前據說過一些樹莓派的傳聞,因而就有了這麼一款鬧鐘。html

須要說明的是,在看這篇文章以前,你至少應該是一個會裝操做系統的程序猿,懂點 Linux,會些 Python,最主要的是你得有一個女友。固然沒有也不要緊,相信看完這篇文章,你也嘗試作了這麼一款鬧鐘,說不定......python

軟硬件清單

  • 讀卡器以及 SD 卡(裝系統用)
  • 音箱一枚,最好支持 3.5mm
  • SSH鏈接工具(SecureCRT,Xshell)
  • 寬帶、路由器(這應該是家中常備了)
  • 裝好系統的樹莓派 3B+ 一隻(充電器、CPU散熱風扇等)

在開始以前先秀一下這半成品的鬧鐘:git

編碼

一個合格的程序員,怎麼能不懂點 Python,雖然作 Java這麼多年,我仍是想用她來開發。程序員

樹莓派 3B+ 的系統默認預裝了 Python3 ,咱們只須要安裝一些第三方依賴就能夠,如下即是主要代碼:shell

__author__ = "小柒"
__blog__ = "https://blog.52itstyle.vip/"
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():
    # 青島天氣,101120201 是青島地區的編碼,其餘地區請自行查找
    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)


# 文字轉語音
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
    })
    # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼
    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("播報天氣")
    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 配置定時任務要設置絕對路徑
            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("播報完畢,起牀啦")
            break


if __name__ == '__main__':
    get_weather()

代碼看不懂,不要緊,來一張清晰的流程圖:json

定時

固然了,鬧鐘可不能本身播放,咱們還須要加入定時任務腳本,實現定時播放。vim

運行crontab -e 標誌來編輯 cron 表api

no crontab for pi - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/ed
  2. /bin/nano        <---- easiest
  3. /usr/bin/vim.tiny

Choose 1-3 [2]: 3

這裏我選擇最熟悉的 Vim 命令進行編輯。app

cron 條目的佈局由六個部分組成:分鐘,小時,月份,月份,星期幾和要執行的命令。dom

# * * * * *  command to execute (要執行的命令)
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── 星期中的哪一天(0-7)(從0到6表明星期日到星期六,也可使用名字;7是星期天,等同於0)
# │ │ │ └────────── 月份 (1 - 12)
# │ │ └───────────────幾號 (1 - 31)
# │ └──────────────────── 小時 (0 - 23)
# └───────────────────────── 分鐘 (0 - 59)

添加一個計劃任務:

# 早上七點
00 07 * * *   python3 /home/pi/alarmClock/play.py

配置完成之後必定要檢查一下時間,新裝系統有可能不是中國時區:

date

更正時區:

# 根據提示選擇 亞洲(Asia)-上海(上海)
sudo dpkg-reconfigure tzdata

小結

其實,這款鬧鐘並不智能,而且還有一些昂貴,幸虧身邊有兩個平時不怎麼用的音箱,就拿來廢物利用了。好處是能夠爲所欲爲的DIY,好比作一款APP,或者後臺管理,進行遠程控制,給予女友無時無刻的關懷。

固然,她可能不單單是一款鬧鐘,你也能夠加入語音喚醒,語音聊天,打造一款全功能的智能機器人。

視頻演示:https://dwz.cn/KQXemuvd

源碼:https://gitee.com/52itstyle/Python

相關文章
相關標籤/搜索