How to schedule simple alarms in Python?


Creating a simple alarm clock is one of the basic projects that can help you understand the basics of time manipulation, running system commands, playing audio files and other such essential topics. And, in this tutorial, we will be learning how to build one.

For this, we will be working with the PyGame module to play the audio file and the datetime module to get the current system time. Alright, let us get started then!

Getting Started

For playing the audio file, we will be using the PyGame module.

This module does not come pre-packaged with Python. So, we’ll be downloading and installing it using the pip package manager.

To install the PyGame module, use the following "pip" command:

pip install pygame

And now, we need to import the mixer module which is part of the PyGame library and initialize it.

from pygame import mixer
mixer.init()

You are all set to start building the alarm.

Building the Alarm Clock

Let us import all the necessary modules first.

import datetime
from pygame import mixer

Next up, we read in the hour, minute, AM or PM details for the alarm from the user.

Hour = int(input("At what hour do you want the alarm? ")) 
Min = int(input("Specify exact minutes ")) 
amPm = str(input("AM or PM? ")) 

Next, if it’s PM, we add 12 to the hour specified in order to convert it to military and standard format.

if (amPm == "pm"): 
	alarmH = alarmH + 12

Next up, we just create an infinite loop and check if the current time matches the time specified and if it does, we ring the alarm music.

while(True):
	if(Hour == datetime.datetime.now().hour and Min == datetime.datetime.now().minute): 
		mixer.music.load("your_audio_file.mp3")
		mixer.music.play()

Don’t forget to initialize the pygame.mixer module before using it −

mixer.init()

And that’s it, you have successfully created a simple alarm clock in Python.

The Complete Code

Now let's see how the full program looks like −

import datetime
from pygame import mixer

mixer.init()

Hour = int(input("At what hour do you want the alarm? "))
Min = int(input("Specify exact minutes "))
amPm = str(input("AM or PM? "))

alarmH = Hour

if (amPm == "pm"):
   alarmH = alarmH + 12

while(True):
   if(alarmH == datetime.datetime.now().hour and Min == datetime.datetime.now().minute):
      mixer.music.load("sample1.mp3")
      mixer.music.play()

Conclusion

Now you know how to build a simple alarm clock using Python. There are additional features that you can add to it, like validating the input provided, adding various music for the time of alarm being played. Probably make it more efficient by scheduling the script using crontab rather than running a while loop.

Updated on: 24-Aug-2023

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements