Pythonでカウントダウンタイマーの
コンソールアプリケーションを作成しました。
時間(分)を指定し、指定時間後にmp3ファイルを再生します。
1分後にsound.mp3を再生するにはcountdown_timer.pyの引数に
1とsound.mp3を指定します。
1 |
python countdown_timer.py 1 sound.mp3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import argparse import time import sys import os from mutagen.mp3 import MP3 import pygame class CountDownTimer: def __init__(self, minutes, mp3_filepath): self.minutes = minutes self.seconds = 0 self.mp3_file_path = mp3_filepath def validate_arg_minutes(self): """引数の時間をチェック""" if self.minutes < 0: print('時間には0以上の整数を入力してください。') return False return True def validate_arg_mp3_filepath(self): """引数のmp3ファイルをチェック""" if self.mp3_file_path == '': print('mp3ファイルのパスを入力してください') return False if not os.path.exists(self.mp3_file_path): print('ファイルが見つかりませんでした。') return False _, ext = os.path.splitext(self.mp3_file_path) if ext != '.mp3': print('拡張子が{}です。mp3ファイルを指定してください。'.format(ext)) return False return True def count_down(self): if not self.validate_arg_minutes(): return if not self.validate_arg_mp3_filepath(): return while self.minutes >= 0 and self.seconds >= 0: print('\r残り時間: {}:{:0>2}'.format(self.minutes, self.seconds), end='') self.seconds -= 1 if self.seconds < 0: self.minutes -= 1 self.seconds = 59 if self.minutes < 0: break time.sleep(1) pygame.mixer.init() pygame.mixer.music.load(self.mp3_file_path) mp3_length = MP3(self.mp3_file_path).info.length print('\n時間になりました') print('終了するにはCtrl+Cを押して下さい') try: while True: pygame.mixer.music.play(1) time.sleep(mp3_length + 0.1) except KeyboardInterrupt: pygame.mixer_music.stop() sys.exit() if __name__ == '__main__': parser = argparse.ArgumentParser(description='引数で指定した時間(分単位)後にmp3ファイルを鳴らす') parser.add_argument('minutes', type=int, help='指定時間(分単位)') parser.add_argument('mp3_file_path', type=str, help='mp3ファイルのパス') args = parser.parse_args() countdown_timer = CountDownTimer(args.minutes, args.mp3_file_path) countdown_timer.count_down() |
コンソールアプリケーションの引数の解析にはsys.argvも使用できますが
argparseがおすすめです。
mp3ファイルを再生する部分はpygameとmutagenを使用してます。
githubにテストコードも含めて置いてあります。
コメント