LoginSignup
2
1

Pythonで時報をしゃべらせよう

Last updated at Posted at 2023-07-04

お手元PCで15分に一回、現在時刻をしゃべってもらいます。

time_signal.py
import time
import pyttsx3

interval_minutes = 15
engine = pyttsx3.init()

def init():
    engine.setProperty("rate",100)
    engine.setProperty('volume',1.0)

    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[1].id)
    
def loop():
    while True:
        current_time = time.localtime()
        if current_time.tm_min % interval_minutes == 0 and current_time.tm_sec == 0:
            say_time(current_time.tm_hour, current_time.tm_min)
            time.sleep((interval_minutes - 1) * 60)
        else:
            time.sleep(1)

def say_time(hour, min):
    engine.say(f'{hour:02}:{min:02}')
    engine.runAndWait()  

if __name__ == "__main__":
    try:
        init()
        loop()
    except KeyboardInterrupt:
        print('KeyboardInterrupt')    

音声について

このコードではリストから1番めの声を決め打ちで選んでいます。
手元では女性英語音声ですが、内容と順番は動作環境によって変わります。
詳しくはこのあたりを。

また、音声の言語圏によってフォーマットと時刻の読み方にも違いがあります。
手元の英語音声ではhh:MM:SSにおいてhが1桁か2桁か、SSをつけるか省くかで変わります。
長くなるので例を列挙します、調整してみてください。

読み方
01:00:00 One o'clock.
1:00:00 One hour.
12:00 Twelve o'clock.
12:00:00 Twelve hours.
1:10:00 One hour and ten minutes.
1:10 One, ten.
2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1