iTunes Sleep Timer – With Fade Out Applescript

I like to listen to music or an audiobook as I fall asleep, but don’t want it to continue playing all night, so I put together this little script to implement an iTunes “Sleep Timer”. It also fades the volume down which makes it very difficult to notice and seems to help falling asleep (could be all in my head though).

How it works: When run it asks how many minutes you want to wait before “going to sleep”. It then waits until “fade_for_minutes” minutes (default is 10) less than the time you specified and starts to fade out iTunes. It pauses after the fade completes, then restores the volume to the setting it was started with.

Run at: 10:00pm
Sleep time: 60 minutes
fade_for_minutes: 10 minutes
initial volume: 100 (iTunes volume ranges from 0 to 100)

At 10:50 fade_sound will start running. It will decrease the iTunes volume by 1 every 6 seconds ((fade_for_minutes*60)/initialVolume).
At 11:00 it will pause the currently playing track, reset the volume to 100, and quit itself.

You can either try to copy/paste the script below in to Applescript Editor, then save as an application and be sure to check off “Stay Open”, or you can download the Application.

property lastSleepLength : 5
property fade_for_minutes : 10

global endTime, initialVolume

on idle
-- Wait until fade_for_minutes before the end time
-- Then call fade_sound which will fade the sound, pause itunes, and reset the volume
set curTime to current date
if ((curTime + (fade_for_minutes * 60)) ≥ endTime) then
my fade_sound()
quit me
end if
return 1
end idle

on run
set endTime to (current date) + getSleepLength()
tell application "iTunes" to set initialVolume to sound volume

on error number -128
-- user canceled
quit me
end try
end run

on fade_sound()
set timeBetweenDecreases to ((fade_for_minutes * 60) / initialVolume)
repeat with i from 0 to initialVolume
delay timeBetweenDecreases
tell application "iTunes" to set the sound volume to (sound volume) - 1
end repeat
my iTunesReset()
end fade_sound

-- Pause iTunes and reset volume
on iTunesReset()
tell application "Finder"
if process "iTunes" exists then
tell application "iTunes"
if player state is playing then
end if
set the sound volume to initialVolume
end tell
end if
end tell
end iTunesReset

-- gets the amount of minutes till we go to sleep
on getSleepLength()
set dialogResult to display dialog "How many minutes till we go to Sleep?" default answer lastSleepLength
if text returned of the dialogResult is not "" then
set sleepLength to text returned of dialogResult as number
exit repeat
end if
end try
end repeat

set lastSleepLength to sleepLength

return (sleepLength * 60) -- Return in seconds
end getSleepLength

1 thought on “iTunes Sleep Timer – With Fade Out Applescript

Leave a Reply

Your email address will not be published.