Is there a way to listen for any key press, and mute microphone?

560 views Asked by At

I'm not familiar with LUA or hammerspoon, but I want to listen for any button on the keyboard being pressed.

I believe I can use hs.eventtap.event.newKeyEvent for this, but I'm not sure how to catch any and all key press. I don't care what is pressed, I just want to mute the microphone, and unmute it once there has been x number of seconds of no key being pressed.

Is this possible with hammerspoon? Please point me in the right direction.

1

There are 1 answers

0
Christophe Geers On

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.