1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Macでアラームをならすcuiコマンドを作成した(してもらった)

1
Last updated at Posted at 2026-01-11

背景

  • 困っていたこと
    私は大事な会議の際、出席を忘れないように携帯でアラームを設定しているのですが、
    毎回携帯で設定するのが手間に感じていた

  • 解決策
    業務で使用している Mac でそのままアラームを設定できれば便利だと考えました。
    さらに、Mac 上でスクリプトを使って複数のアラームをまとめて設定できれば、より手間を省けるのではないかとも考えました。

コマンド

BingAIを使用して作成しました。

alarm() {
    local input="$1"
    local seconds=0

    if [[ "$input" =~ ^[0-9]{1,2}:[0-9]{2}$ ]]; then
        # 1. 時刻指定 (15:30 など)
        local target_epoch=$(date -j -f "%H:%M" "$input" +%s)
        local now_epoch=$(date +%s)
        seconds=$(( target_epoch - now_epoch ))
        # 今日の時間を過ぎていたら → 明日の同じ時間まで待。そのために 86400 秒(24 時間)を足す
        [[ $seconds -le 0 ]] && seconds=$(( seconds + 86400 ))
    else
        # 2. 期間指定 (10s, 5m, 1h など)
        # 数字部分のみを抽出
        local num=$(echo "$input" | sed 's/[^0-9]//g')
        # 単位(最後の1文字)を抽出
        local unit=$(echo "$input" | sed 's/.*\(.\)$/\1/')

        case "$unit" in
            h) seconds=$(( num * 3600 )) ;;
            m) seconds=$(( num * 60 )) ;;
            s|*) seconds=$num ;; # 単位なし、またはsの場合は秒
        esac
    fi

    # 万が一計算失敗して空になった場合のガード
    if [[ -z "$seconds" || "$seconds" -eq 0 && "$input" != "0" ]]; then
        echo "エラー: 時間を解析できませんでした。"
        return 1
    fi

    echo "$input にセットしました(${seconds}秒後に開始します)。"

    # 3. 実行部分
    (
        sleep $seconds && {
            # 音をバックグラウンドで開始
            while :; do afplay /System/Library/Sounds/Ping.aiff; done &
            local SOUND_PID=$!

            # ダイアログ表示
            osascript -e "display dialog \"$input になりました\" buttons {\"停止\"} default button \"停止\"" > /dev/null 2>&1

            # 停止ボタンが押されたら音を止める
            kill $SOUND_PID
        }
    ) &
}

実行例

  • コマンド
kubota_akihiro:~ $ alarm 19:49
19:49 にセットしました(120秒後に開始します)。
[1] 48110
kubota_akihiro:~ $
  • 結果
    アラーム音が鳴った上で以下のダイアログが表示される。停止ボタンを押下すると、アラームが停止する。
    image.png

改善点

  • 細かい秒数までは指定できていない。
kubota_akihiro:~ $ alarm 19:45
19:45 にセットしました(120秒後に開始します)。
[1] 48110
kubota_akihiro:~ $ alarm 19:46
19:46 にセットしました(180秒後に開始します)。
[2] 48118
kubota_akihiro:~ $ alarm 19:47
19:47 にセットしました(240秒後に開始します)。
[3] 48128
  • ダイアログ表示は時間しかでないので、何の予定なのかも入れられると良い。
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?