Created
March 24, 2020 02:29
-
-
Save innateessence/f846a51ca85a53bacb065faa0f6bcd4e to your computer and use it in GitHub Desktop.
A simple alarm script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import time | |
import wave | |
import pyaudio | |
''' | |
>_ python pyalarm "8:00 PM" | |
>_ python pyalarm "20:00" | |
''' | |
class Alarm(object): | |
def __init__(self, alarm_time): | |
self.current_seconds = self.time_str_to_seconds(time.strftime('%I:%M %p')) + int(time.strftime('%S')) | |
self.alarm_seconds = self.time_str_to_seconds(alarm_time) | |
self.sleep_time = self.alarm_seconds - self.current_seconds | |
if self.sleep_time < 0: | |
self.sleep_time += 86400 # 24 hours | |
print("Sleeping for {} seconds".format(self.sleep_time)) | |
time.sleep(self.sleep_time) | |
print("Sounding Alarm") | |
self.sound_alarm() | |
def time_str_to_seconds(self, s): | |
hour = s.split(':')[0] | |
min = s.split(':')[1] | |
if 'AM' in min: | |
min = min.split(' ')[0] | |
if 'PM' in min: | |
min = min.split(' ')[0] | |
hour = int(hour) + 12 # convert to military time | |
return (3600 * int(hour)) + (int(min) * 60) # convert to seconds | |
def sound_alarm(self, fp='alarm.wav'): | |
#define stream chunk | |
chunk = 1024 | |
#open a wav format music | |
with wave.open(fp, 'rb') as f: | |
#instantiate PyAudio | |
p = pyaudio.PyAudio() | |
#open stream | |
stream = p.open(format=p.get_format_from_width(f.getsampwidth()), | |
channels=f.getnchannels(), | |
rate=f.getframerate(), | |
output=True) | |
#read data | |
data = f.readframes(chunk) | |
#play stream | |
while data: | |
stream.write(data) | |
data = f.readframes(chunk) | |
#stop stream | |
stream.stop_stream() | |
stream.close() | |
#close PyAudio | |
p.terminate() | |
if __name__ == '__main__': | |
Alarm(sys.argv[-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment