Python3 循环定时休息并播放音乐 (Windows)

功能:工作一段时间(40 min),自动定时休息(10 min)并播放音乐,如此循环

文件名EyeTimer.pyw,直接双击运行

关闭方法:在任务管理器里结束 Python 进程

#coding=utf-8

from ctypes import *
from ctypes.wintypes import *
import time, easygui as g
import os
import pygame
import random
import linecache
 
HWND_BROADCAST = 0xffff
WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170
MonitorPowerOff = 2
SW_SHOW = 5
 
def main():
  boolLongTime = False
  user32 = windll.LoadLibrary('user32.dll')
  shell32 = windll.LoadLibrary("shell32.dll")
  stopMusic = 'stop.wav'
  count = len(open('mp3_list.txt', 'rU',encoding='utf-8').readlines())

  while 1:  
    if boolLongTime == False:
      time.sleep(40 * 60)  #工作 40 min

      g.msgbox("可以休息一下了", title="提醒",ok_button="确定")        
      
      pygame.mixer.init()
      pygame.mixer.music.load(stopMusic)
      pygame.mixer.music.play()
      pygame.time.delay(10000)	
			
      #取随机数,以便随机播放mp3_list.txt中的任一首
      randomfile = random.randint(0, count)

      path1 = linecache.getline('mp3_list.txt', randomfile)	
      path1 = path1.replace('\\', '//')
      path1 = path1.replace('\n', '')
			
      pygame.mixer.music.load(path1.encode())
      pygame.mixer.music.play()

      #调用 API 实现 锁屏,熄屏
      #PostMessageW(hWnd,WM_RECVDATA,0,(LPARAM)tempBuf)
      windll.user32.PostMessageW(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MonitorPowerOff)   
      shell32.ShellExecuteW(None,'open', 'rundll32.exe', 'USER32,LockWorkStation','',SW_SHOW)
      
      boolLongTime = True
    else:
      time.sleep(10 * 60)  #休息10 min
      pygame.mixer.init() 
      pygame.mixer.music.load(stopMusic)
      pygame.mixer.music.play()
      pygame.time.delay(10000)
      
      pygame.mixer.music.stop()
      boolLongTime = False
 
if __name__ == "__main__":
    main()

Comments are closed.