I use the following to toggle my audio input devices between muted and unmuted.
function toggleMute()
local mic = hs.audiodevice.defaultInputDevice();
local state = not mic:muted()
hs.fnutils.each(hs.audiodevice.allInputDevices(), function(device)
device:setInputMuted(state)
end)
if mic:muted() then
hs.alert('Muted')
else
hs.alert('Unmuted')
end
end
local hyper = {"⌥", "⌃"}
hs.hotkey.bind(hyper, "m", function() toggleMute() end)
That will toggle between muted and unmuted when you press ⌥+⌃+m.
If you want to automatically mute after X seconds of no keyboard activity, then have a look at the hs.eventtap
documentation.
https://www.hammerspoon.org/docs/hs.eventtap.event.html
You could set up a listener for key up (keyUp
) or key down (key down
) events.
keyboardTracker = hs.eventtap.new({ events.keyDown }, function (e)
...
end
keyboardTracker:start() // start monitoring the keyboard
keyboardTracker:stop() // stop monitoring the keyboard
To accomplish this:
- create a timer for X seconds (see hs.timer)
- start the timer
- setup an event tap for the
keyDown
event type
- start the event tap
- every time you detect a key down event reset the timer
- when the timer is triggered mute the audio input device and stop the timer
Once the timer has triggered it will mute the audio input devices and stop the timer. After that as soon as you press a key on the keyboard the timer will be restarted.
For example:
local timer = hs.timer.new(5, mute)
function mute()
hs.fnutils.each(hs.audiodevice.allInputDevices(), function(device)
device:setInputMuted(false)
end)
hs.alert('Muted')
timer:stop()
end
timer:start()
local events = hs.eventtap.event.types
keyboardTracker = hs.eventtap.new({ events.keyDown }, function (e)
timer:stop()
timer:start()
end)
keyboardTracker:start()
Reacting to mouse events is similar.