Skip to content

Instantly share code, notes, and snippets.

@sankim
Forked from fbender/sleep-timer.scpt
Last active March 5, 2024 09:55
Show Gist options
  • Select an option

  • Save sankim/26b9649f1dab4ccb1541ffcfdb4d5d7e to your computer and use it in GitHub Desktop.

Select an option

Save sankim/26b9649f1dab4ccb1541ffcfdb4d5d7e to your computer and use it in GitHub Desktop.
AppleScript to put your Mac to sleep after X minutes, fading out the system volume shortly before sleeping. Can be turned into an app via the "Export" feature of the AppleScript Editor.
-- written by Florian Bender, 2015
-- forked and edited by San Kim, 2019
-- based on work by Michael Wyszomierski <https://wysz.com/wyszdom/2009/06/simple-sleep-timer-with-applescript/>
-- license: Public Domain / CC0 <http://creativecommons.org/publicdomain/zero/1.0/>
tell application "System Events"
set fadeTime to 10 -- time in seconds for fade change
-- display alert "Volume: " & volumeValue & ", Delta: " & fadeChange
display dialog "Sleep time (min):" default answer "60"
delay ((text returned of the result) * 60 - 30)
display notification "Going to sleep in 30 sec" with title "Sleep Timer"
delay (30 - fadeTime)
set volumeSettings to get volume settings
set volumeValue to (output volume of volumeSettings)
set fadeChange to (volumeValue div fadeTime)
repeat with X from 1 to fadeTime
set volumeValue to (volumeValue - fadeChange)
set volume output volume volumeValue
delay 1
end repeat
sleep -- alternatively: do shell script "pmset sleepnow"
end tell
@sankim
Copy link
Copy Markdown
Author

sankim commented Apr 15, 2019

@fbender

The main change I made is moving set volumeSettings, set volumeValue, and set fadeChange down, to right before the fadeout starts.

Previously, the fade out would start at the volume level defined at script initiation. So if you run the script when the system volume is set high, and then you manually decrease the volume, the script would increase the volume to the original level before fading out.

Now, it starts the fade out at whatever level the volume is, at the time the fadeout starts.

Thanks for providing the script, it's been super helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment