[play Python] create an intelligent voice alarm clock for girlfriend

Before reading this article, you should be at least a program ape that can install the operating system. You should know Linux, Python, and most importantly, you should have a girlfriend. Of course, it doesn't matter. After reading this article, you try to make such an alarm clock. Maybe...

Software and hardware list

  • Card reader and SD card (for system installation)
  • One speaker, preferably 3.5mm
  • SSH connection tool (SecureCRT, Xshell)
  • Broadband, router
  • Install the system's bramble pie 3B + one (charger, CPU cooling fan, etc.)

Show the semi-finished alarm clock before you start:

Code

How can a qualified programmer not understand Python? Although I have been doing Java for so many years, I still want to use her to develop.

By default, python 3 is pre installed in the system of raspberry pie 3B +, we only need to install some third-party dependencies, and the following is the main code:

import time
import random
import os
import pygame
import urllib.request
import json
from aip import AipSpeech

"""
//Raspberry school makes intelligent alarm clock
pip3 install pygame
pip3 install baidu-aip
"""


# Weather acquisition
def get_weather():
    # Qingdao weather, 101120201 is the code of Qingdao area. Please find it by yourself in other areas
    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 = 'Dear: it's time to get up. Don't sleep. It's going to be a pig. Hahahaha, I miss you. Do you miss me? The temperature in Qingdao is {} reach {},weather {}'
    weather = weather.format(rt['temp1'], rt['temp2'], rt['weather'])
    if 'rain' in weather:
        weather += 'Don't forget to bring an umbrella today!'
    du_say(weather)


# Text to speech
def du_say(weather):
    app_id = '****'
    api_key = '****'
    secret_key = '****'
    client = AipSpeech(app_id, api_key, secret_key)
    # per 3 It's man 4. It's sister. spd It's speed. vol It's volume.
    result = client.synthesis(weather, 'zh', 1, {
        'vol': 5, 'per': 3, 'spd': 4
    })
    # If the recognition is correct and the voice binary error is returned, dict Refer to the following error codes
    if not isinstance(result, dict):
        with open('weather.mp3', 'wb') as f:
            f.write(result)
    py_game_player('weather.mp3')


# Play weather and music
def py_game_player(file):
    pygame.mixer.init()
    print("Broadcast weather")
    pygame.mixer.music.load(file)
    pygame.mixer.music.play(loops=1, start=0.0)
    print("Play music")
    while True:
        if pygame.mixer.music.get_busy() == 0:
            # Linux To configure a scheduled task, set the absolute path
            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("It's over. Get up.")
            break


if __name__ == '__main__':
    get_weather()

#A set of small knitting Python Information and PDF,Need Python Learning materials can be added to learning group: 631441315. Anyway, it's also idle. It's better to learn something.~~

 

 

It doesn't matter if you don't understand the code. Here is a clear flow chart:

timing

Of course, the alarm clock can't play by itself. We also need to add timing task script to realize timing play.

Run the crontab -e flag to edit the cron table

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

Here I choose the most familiar Vim command for editing.

The layout of the cron entry consists of six parts: minute, hour, month, month, day of the week and the command to be executed.

#***** command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
#Which day of the week (0-7) (from 0 to 6 for Sunday to Saturday, you can also use the name; 7 is Sunday, equivalent to 0)
#Month (1-12)
#Number (1-31)
#└────────────── hours (0 - 23)
# ------------------- minutes (0 - 59)

Add a scheduled task:

# Seven in the morning.
00 07 * * *   python3 /home/pi/alarmClock/play.py

After configuration, check the time. The newly installed system may not be in China's time zone:

date

Correct time zone:

# Select Asia as prompted-Shanghai(Shanghai)
sudo dpkg-reconfigure tzdata

Summary

In fact, this alarm clock is not intelligent, and there are some expensive ones. Fortunately, there are two loudspeakers that are not usually used, so they are used for waste. The advantage is that you can DIY as you like, such as making an APP, or backstage management, remote control, and giving your girlfriend all the time care.

Of course, she may not only be an alarm clock, you can also join voice wake-up, voice chat, and build a full-featured intelligent robot.

Keywords: Python Linux JSON crontab

Added by kr3m3r on Wed, 16 Oct 2019 10:42:58 +0300