酷玩Python,为女朋友打造一款智能语音闹钟,女朋友:滚

警告,在看这篇文章之前,你得先去找一个女朋友,哈哈哈,当然没有的话,也是可以的,而且你也得会操作系统的安装,懂些Linux,等你尝试做出来了,说不定............(期待神评),也需要一些树莓派设备

软硬件清单

读卡器以及 SD 卡(装系统用)
音箱一枚,最好支持 3.5mm
SSH连接工具(SecureCRT,Xshell)
宽带、路由器(这应该是家中常备了)
装好系统的树莓派 3B+ 一只(充电器、CPU散热风扇等)

树莓派 3B+ 的系统默认预装了 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)


# 文字转语音
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()

#小编整理一套Python资料和PDF,有需要Python学习资料可以加学习群:766545907,反正闲着也是闲着呢,不如学点东西啦~~

其实,这款闹钟并不智能,并且还有一些昂贵,幸好身边有两个平时不怎么用的音箱,就拿来废物利用了。好处是可以随心所欲的DIY,比如做一款APP,或者后台管理,进行远程控制,给予女朋友无时无刻的关怀。

你可能感兴趣的:(酷玩Python,为女朋友打造一款智能语音闹钟,女朋友:滚)