Jan. 29, 2012 at 1:43pm View comments

iTunes Sleep Timer

Here is a simple AppleScript that will smoothly fade out your music and then pause iTunes and optionally sleep your Mac.

There are a few nice things about this script:

  • Lets you choose to sleep the machine or not at the end.
  • Puts iTunes back to its original volume after pausing it at the end.
  • Waits half of the time before starting the gradual fade, so you can enjoy the music at normal volume for a while.
  • Will default to 30 minutes if you run it but forget to click the dialog.
  • Works with AirPlay speaker setups since it uses iTunes’ master volume to do the fade.

Open up your AppleScript editor and paste this in, then save as an application.

property default_minutes : 30
property wait_percent : 50 -- wait before starting fade

set question to "Set a sleep timer for how many minutes?"
set options to {"Don't sleep after", "Sleep after", "Cancel"}

display dialog question default answer default_minutes ¬
    buttons options default button 1 giving up after 30
set {_button, _answer} to {button returned, text returned} of result

if _button = "Cancel" then return

set sleep_after to false
if _button = "Sleep after" then set sleep_after to true

try
    set sleep_seconds to _answer * 60
on error
    beep
    display dialog ¬
        "TIMER NOT RUNNING. You didn't enter a number." with icon stop ¬
        buttons {"Quit"} default button 1
    return
end try

set steps to 60
set wait_before_fading to (sleep_seconds * (wait_percent / 100))
set fade_time_step to ((sleep_seconds - wait_before_fading) / steps)

delay wait_before_fading

tell application "iTunes"
    set init_volume to sound volume
    repeat with i from 0 to steps
        set sound volume to (init_volume - (i * init_volume / steps))
        delay fade_time_step
    end repeat
    pause
    set sound volume to init_volume
end tell

if sleep_after then tell application "Finder" to sleep

When you want to use it, start your music in iTunes, set it to a comfortable volume, then run the app.

If you want to cancel the timer once it’s running, you have to either hit Command-. (Command-Period) within the app, or force-quit the app with Command-Option-ESC.

blog comments powered by Disqus