好友
阅读权限20
听众
最后登录1970-1-1
|
本帖最后由 shzjz123 于 2025-11-20 12:12 编辑
[Python] 纯文本查看 复制代码 import json
import os
import time
import datetime
import schedule
import threading
import sys
# 尝试导入音频播放模块(优先 pygame,兼容性好)
try:
import pygame
HAS_AUDIO = True
except ImportError:
HAS_AUDIO = False
print("⚠️ 未安装 pygame,将仅打印提示。安装命令:pip install pygame")
# 全局变量
CONFIG_FILE = "config.json"
config = None
today_schedule = []
def load_config():
global config
if not os.path.exists(CONFIG_FILE):
print(f"❌ 配置文件 {CONFIG_FILE} 不存在!")
sys.exit(1)
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
def get_todays_bell_times():
"""根据今天日期返回应打铃的时间列表"""
today = datetime.date.today()
today_str = today.isoformat() # e.g., "2025-11-20"
# 检查是否为自定义日期
if today_str in config["schedule"]["custom_days"]:
return config["schedule"]["custom_days"][today_str]
# 判断是工作日还是周末(周一=0, 周日=6)
weekday = today.weekday()
if weekday < 5: # 周一到周五
return config["schedule"]["weekdays"]
else:
return config["schedule"]["weekends"]
def ring_bell():
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"🔔 {now} —— 打铃!")
sound_file = config.get("sound_file", "bell_sound.mp3")
if HAS_AUDIO and os.path.exists(sound_file):
try:
pygame.mixer.init()
pygame.mixer.music.load(sound_file)
vol = config.get("volume", 0.8)
pygame.mixer.music.set_volume(vol)
pygame.mixer.music.play()
# 等待播放结束(最多10秒)
for _ in range(50):
if not pygame.mixer.music.get_busy():
break
time.sleep(0.2)
pygame.mixer.quit()
except Exception as e:
print(f"🔊 播放铃声出错: {e}")
else:
if not HAS_AUDIO:
print("📢(提示:安装 pygame 可播放铃声)")
elif not os.path.exists(sound_file):
print(f"📢(铃声文件 {sound_file} 不存在)")
def setup_daily_schedule():
global today_schedule
schedule.clear() # 清除旧任务
bell_times = get_todays_bell_times()
today_schedule = bell_times[:]
for t in bell_times:
try:
# schedule 要求格式为 HH:MM
datetime.datetime.strptime(t, "%H:%M")
schedule.every().day.at(t).do(ring_bell)
except ValueError:
print(f"⚠️ 时间格式错误,跳过: {t}")
day_type = "工作日" if datetime.date.today().weekday() < 5 else "周末"
custom_note = "(自定义日)" if datetime.date.today().isoformat() in config["schedule"]["custom_days"] else ""
print(f"✅ 已加载今日 ({datetime.date.today()}) 打铃计划 [{day_type}{custom_note}]:{len(bell_times)} 次")
print("⏰ 时间点:" + ", ".join(bell_times) if bell_times else "无")
def daily_scheduler():
"""每天凌晨重新加载计划"""
while True:
now = datetime.datetime.now()
next_day = now.replace(hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1)
sleep_seconds = (next_day - now).total_seconds()
time.sleep(sleep_seconds)
print("\n📅 新的一天,重新加载打铃计划...")
setup_daily_schedule()
def run_pending():
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
print("🏫 学校智能打铃系统启动中...")
load_config()
# 初始化今日计划
setup_daily_schedule()
# 启动后台线程
threading.Thread(target=run_pending, daemon=True).start()
threading.Thread(target=daily_scheduler, daemon=True).start()
print("🟢 系统运行中... 按 Ctrl+C 退出")
try:
while True:
time.sleep(10)
except KeyboardInterrupt:
print("\n🛑 打铃系统已停止。")
sys.exit(0)
安装依赖(首次运行)pip install schedule pygame附可修改任意时间配置文件和简单的铃声文件
找一个铃声文件,改为bell_sound.mp3即可使用 |
-
-
config.txt
460 Bytes, 下载次数: 3, 下载积分: 吾爱币 -1 CB
用的时候改为.json
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|
|