1

我写了一个spoon脚本来控制音量,但是hotkeys.bind方法不起作用,是什么问题?

这是init.lua勺子的

-- === Volume ===

local obj={}
obj.__index = obj

-- Metadata
obj.name = "Volume"
obj.version = "1.0"
obj.license = "MIT - https://opensource.org/licenses/MIT"

obj.logger = hs.logger.new('Volume')

function obj:init()
end

function obj:changeVolume(diff)
   return function()
     local current = hs.audiodevice.defaultOutputDevice():volume()
     local new = math.min(100, math.max(0, math.floor(current + diff)))
     if new > 0 then
       hs.audiodevice.defaultOutputDevice():setMuted(false)
     end
     hs.alert.closeAll(0.0)
     hs.alert.show("Volume " .. new .. "%", {}, 0.5)
     hs.audiodevice.defaultOutputDevice():setVolume(new)
   end
 end

return obj

我把这个勺子装进去并用~/.hammerspoon/init.lua

hs.loadSpoon("Volume")
hs.hotkey.bind({'cmd', 'alt'}, '[', function() spoon.Volume:changeVolume(-3) end)
hs.hotkey.bind({'cmd', 'alt'}, ']', function() spoon.Volume:changeVolume(3) end)
4

1 回答 1

1

changeVolume方法被调用时,它返回一个函数,但不执行它。要使其工作,您唯一需要做的就是从顶部和底部删除第二行,这样当函数被调用时,它将被执行:

function obj:changeVolume(diff)
    local current = hs.audiodevice.defaultOutputDevice():volume()
    local new = math.min(100, math.max(0, math.floor(current + diff)))
    if new > 0 then
        hs.audiodevice.defaultOutputDevice():setMuted(false)
    end
    hs.alert.closeAll(0.0)
    hs.alert.show("Volume " .. new .. "%", {}, 0.5)
    hs.audiodevice.defaultOutputDevice():setVolume(new)
 end

请注意,建议的方法是公开:bindHotKeys()方法。我建议将changeVolume函数设为本地(local function changeVolume),然后公开inc()dec()方法:

local function changeVolume(diff)
...
end

function obj:inc()
    changeVolume(3)
end

function obj:dec()
    changeVolume(-3)
end

function obj:bindHotkeys(mapping)
    local spec = {
        inc = hs.fnutils.partial(self.inc, self),
        dec = hs.fnutils.partial(self.dec, self),
      }
      hs.spoons.bindHotkeysToSpec(spec, mapping)
      return self
end

于 2021-05-06T00:53:10.197 回答