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
-- 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
set endTime to (current date) + getSleepLength()
tell application "iTunes" to set initialVolume to sound volume
on error number -128
-- user canceled
set timeBetweenDecreases to ((fade_for_minutes * 60) / initialVolume)
repeat with i from 0 to initialVolume
tell application "iTunes" to set the sound volume to (sound volume) - 1
-- Pause iTunes and reset volume
tell application "Finder"
if process "iTunes" exists then
tell application "iTunes"
if player state is playing then
set the sound volume to initialVolume
-- gets the amount of minutes till we go to sleep
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
set lastSleepLength to sleepLength
return (sleepLength * 60) -- Return in seconds