Created
August 27, 2020 16:00
-
-
Save creachadair/613c1ae65e9a9c81adda7f624f2ef31e to your computer and use it in GitHub Desktop.
Hammerspoon script for "timed mute"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| do | |
| local log = hs.logger.new('mutation', 'info') | |
| local cmd_shift = {"cmd", "shift"} | |
| -- Mute or unmute the speaker according to the truth of t. | |
| local function mute(t) | |
| return string.format("set volume %s output muted", | |
| t and "with" or "without") | |
| end | |
| -- Run the specified thunk and report how long it took in seconds. | |
| local function time(fn) | |
| local start = hs.timer:absoluteTime() | |
| fn() | |
| local stop = hs.timer:absoluteTime() | |
| return (stop - start) / 1e9 -- nanoseconds to seconds | |
| end | |
| -- Run script via the AppleScript interpreter. | |
| local function run(script) | |
| return time(function () hs.osascript.applescript(script) end) | |
| end | |
| --[[ | |
| Mute the speakers for sec seconds. If the speakers are already muted, add | |
| sec to the amount of time they will remain muted. | |
| To allow mutes to "stack", keep a persistent timer, and add the designated | |
| value to what is already there. Since hammerspoon is single threaded we do | |
| not have to worry about races. | |
| ]] | |
| local timer = hs.timer.new(0, function () | |
| run(mute(false)) | |
| log.f('Sound unmuted') | |
| end) | |
| local function silence(sec) | |
| -- Always mute, in case the user manually unmuted. | |
| local delta = run(mute(true)) | |
| if not timer:running() then log.f('Sound muted') end | |
| -- Pin the timer at 0, since a stopped timer will have a next trigger | |
| -- sometime in the past. | |
| local left = timer:setNextTrigger( | |
| math.max(timer:nextTrigger(), 0) + sec - delta):nextTrigger() | |
| log.f('Time remaining now: %.1f sec', left) | |
| end | |
| -- Error correction when an interstitial turns out to be a full. | |
| hs.hotkey.bind(cmd_shift, '8', function () silence(10) end) | |
| -- Interstitials after a manual skip. | |
| hs.hotkey.bind(cmd_shift, '9', function () silence(15) end) | |
| -- Normal random interval. | |
| hs.hotkey.bind(cmd_shift, '0', function () silence(59.5) end) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment