具备跨平台能力,目前在一台树莓派3B+上使用,带着公司音响,每天定时做操,放音乐
import os
import random
import re
import sys
import time
from datetime import datetime
import pygame
import requests
import simpleaudio
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
from bs4 import BeautifulSoup
_dir = os.path.dirname(os.path.abspath(__file__))
playlist_path = os.path.join(_dir, 'media')
mlist = []
m_play_list = []
MUSIC_END = pygame.USEREVENT + 1
def random_file():
rad = random.randint(0, len(mlist) - 1)
print(rad)
mfile = mlist[rad]
return mfile
def load_play_list():
print("load_play_list")
for iroot, idir, flist in os.walk(playlist_path):
for f in flist:
if f.find("mp3") != -1:
mlist.append(os.path.join(iroot, f))
else:
print("No Mp3 !")
print(mlist)
play_music()
def search_music():
print("search_music")
def job():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def start_exercises():
print("start_exercises")
stop_music()
wave_obj = simpleaudio.WaveObject.from_wave_file(playlist_path + "/zuocao.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
def play_music():
print("music first_play")
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
mfile = random_file()
m_play_list.append(mfile)
print(mfile)
pygame.mixer_music.fadeout(1)
pygame.mixer_music.load(mfile)
pygame.mixer.music.set_volume(0.1)
pygame.mixer.music.set_endevent(MUSIC_END)
pygame.mixer.music.play()
for num in range(1, 11):
time.sleep(0.5)
vol = num / 10
print(vol)
pygame.mixer.music.set_volume(vol)
def continue_music():
print("continue_music")
mfile = random_file()
m_play_list.append(mfile)
print(mfile)
pygame.mixer_music.fadeout(1)
pygame.mixer_music.load(mfile)
pygame.mixer.music.set_volume(1)
pygame.mixer.music.set_endevent(MUSIC_END)
pygame.mixer.music.play()
def end_music():
print("end_music")
pygame.mixer.music.set_endevent()
def stop_music():
print("end_music")
pygame.mixer.music.stop()
def main():
scheduler = BackgroundScheduler()
print("main")
scheduler.remove_all_jobs()
scheduler.add_job(load_play_list, 'cron', day_of_week='0-6', hour=13, minute=25)
scheduler.add_job(start_exercises, 'cron', day_of_week='0-6', hour=13, minute=29)
scheduler.add_job(load_play_list, 'cron', day_of_week='0-6', hour=15, minute=15)
scheduler.add_job(end_music, 'cron', day_of_week='0-6', hour=15, minute=30)
scheduler.add_job(load_play_list, 'cron', day_of_week='0-6', hour=16, minute=16)
scheduler.add_job(end_music, 'cron', day_of_week='0-6', hour=16, minute=31)
scheduler.start()
print("pygame_init")
pygame.mixer.init()
pygame.display.set_mode([500, 300])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == MUSIC_END:
print('music end event')
continue_music()
if __name__ == '__main__':
print(playlist_path)
main()