Skip to content

Commit

Permalink
Add AutoMuteOnSleep (#267)
Browse files Browse the repository at this point in the history
* Add AutoMuteOnWake

* Convert tabs to spaces

* Add trailing space

* Misc improvements

– Mute on `systemWillSleep` as well. This makes sure that sound doesn't play for a split second on wake. Also makes it more robust since we're muting all devices twice (if one of the two events doesn't trigger properly for example).
– Set the volume to `0`, and only actually mute if setting the volume to 0 failed. It's more convenient to increase the volume starting from 0 in my experience than restoring the previous sound level.

* Rename spoon to AutoMuteOnSleep

* AutoMuteOnWake → AutoMuteOnSleep

* Update init.lua
  • Loading branch information
devnoname120 authored Aug 7, 2024
1 parent 069175a commit acf4600
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Source/AutoMuteOnSleep.spoon/init.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
--- === AutoMuteOnSleep ===
---
--- Automatically set to 0 the volume of all output audio devices except Bluetooth devices when Mac goes to sleep.
--- Useful to avoid blasting sound when opening a Macbook in the public transport.
--- Note: This is primarily intended for portable Mac devices, which have internal speakers.
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/AutoMuteOnSleep.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/AutoMuteOnSleep.spoon.zip)


local obj={}
obj.__index = obj

-- Metadata
obj.name = "AutoMuteOnSleep"
obj.version = "1.0"
obj.author = "devnoname120 <[email protected]"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"

obj.sleepWatcher = nil

local function muteNonBluetoothOutputDevices(state)
if state == hs.caffeinate.watcher.systemDidWake or state == hs.caffeinate.watcher.systemWillSleep then
local devices = hs.audiodevice.allOutputDevices()

for _, device in ipairs(devices) do
if device and device:transportType() ~= 'Bluetooth' then
_ = device:setVolume(0) or device:setMuted(true)
end
end
end
end


function obj:init()
self.sleepWatcher = hs.caffeinate.watcher.new(muteNonBluetoothOutputDevices)
end

function obj:start()
self.sleepWatcher:start()
end

function obj:stop()
self.sleepWatcher:stop()
end

return obj

0 comments on commit acf4600

Please sign in to comment.