简体   繁体   中英

How to stop the alarm when key pressed?

I'm trying to write a python code for alarm clock. I've 2 doubts -
1) Comparison between local time and user input time doesn't occur unless i add a 0 before every single digit number. Ex- h:m:s = 08:09:35. It's not working if i type - 8:9:35
2)How can i stop an alarm when any key is pressed? "input" command isn't working.

code:

#strfime is of type string
#localtime is of time int

#using strftime
import time
from pygame import mixer

def sound():
    mixer.init()
    mixer.music.load("F:\learn\python\music1.mp3")  #file is 28 seconds long

def userinput():

    print("current time is: ",time.strftime("%H:%M:%S"))  
    h=(input("Enter the hour: "))               
    m=(input("Enter the minutes: "))
    s=(input("Enter the seconds: "))
    alarm(h,m,s)


def alarm(h,m,s):  
    n=2                         #rings twice in 1 minute.

    while True: 
        if time.strftime("%H") == h and time.strftime("%M") == m and time.strftime("%S") == s:

            print("wake up!!!! \n")
            break

    sound()
    while n>0:                                  #code for ringing twice in a minute.
        mixer.music.play()
        time.sleep(30)                          #alarm should stop when any key pressed.
        mixer.music.stop()
        n-=1


    snooze_in = input("Do you want to snooze? press y or n. ")

    if snooze_in == 'y':
        print("The alarm will start in 5 seconds")
        time.sleep(5)               #snooze for x seconds
        h=time.strftime("%H")
        m=time.strftime("%M")
        s=time.strftime("%S")

        return alarm(h,m,s)

    else:
        exit()    



if __name__=="__main__":
    userinput()

You could use datetime objects and then subtract the start from the end datetime to get a timedelta object. Afterwards use the total_seconds of the timedelta to calculate the end time in milliseconds (by adding it to pygame.time.get_ticks() ) and play the alarm sound when the alarm time - pygame.time.get_ticks() is less than 0.

To stop the timer you could put the timer code into an if clause ( if timer_active: ) and set timer_active = False when the user presses a key ( S in the example below).

import datetime
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
SOUND = pg.mixer.Sound(r"C:\Dokumente\Pythonprogramme\win3.wav")


def main():
    start = datetime.datetime.now()
    print("current time is: ", start)
    h = int(input("Enter the hour: "))
    m = int(input("Enter the minutes: "))
    s = int(input("Enter the seconds: "))
    # I just pass the current year, month and day here, so it'll
    # work only if the end time is on the same day.
    end = datetime.datetime(start.year, start.month, start.day, h, m, s)
    timedelta = end-start
    alarm_time = pg.time.get_ticks() + timedelta.total_seconds()*1000
    repeat_time = 3000  # Repeat the alarm after 3000 ms.
    timer_active = True

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_s:
                    # Stop the sound and the timer.
                    SOUND.stop()
                    timer_active = False

        if timer_active:
            if alarm_time - pg.time.get_ticks() < 0:  # Time is up.
                SOUND.play()  # Play the sound.
                # Restart the timer by adding the repeat time to the current time.
                alarm_time = pg.time.get_ticks() + repeat_time

        screen.fill(BG_COLOR)
        pg.display.flip()
        clock.tick(60)


if __name__ == '__main__':
    main()
    pg.quit()

Note that this example works only if the end time is on the same day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM