python定时播放音乐
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import time import pygame import os import random import logging from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.blocking import BlockingScheduler def play_music(music_file): try: pygame.mixer.init() pygame.mixer.music.load(music_file.encode('utf-8')) pygame.mixer.music.play() pygame.mixer.music.set_volume(1) while True: if pygame.mixer.music.get_busy(): time.sleep(1) else: print("file play over") return finally: pass def play_all(): try: music_list = [] # 获取文件运行路径 path = os.path.split(os.path.realpath(__file__))[0] # 获取music文件夹路径 music_path = path + '/musics' # 将文件添加至播放队列 for f in os.listdir(music_path): tmp_path = os.path.join(music_path, f) if not os.path.isdir(tmp_path): music_list.append(tmp_path) # 随机打乱队列 random.shuffle(music_list) # 依次播放 for music in music_list: play_music(music) finally: pass if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s', datefmt='%Y/%m/%d %H:%M:%S') logger = logging.getLogger('%s' % 'job') logger.info("start!") while True: try: sched = BlockingScheduler() # 添加定时播放音乐的任务 sched.add_job(play_all, 'cron', day_of_week='*', hour='23', minute="47", second="0") sched.start() finally: pass logger.info("end!")