[新教程] 利用Hammerspoon解决AirPods连接mac默认音量过大的问题

背景

每次AirPods连接MAC都会被音量吓一跳。

步骤

1、安装Hammerspoon。

brew install hammerspoon --cask

2、创建默认配置。

mkdir -p ~/.hammerspoon
touch ~/.hammerspoon/init.lua

3、在init.lua中写入配置

-- 存储上一次默认音频输出设备的名称
local lastOutputDeviceName = hs.audiodevice.defaultOutputDevice():name()

-- 处理设备变更的回调函数
local function handleDeviceChanges()
-- 获取当前默认音频输出设备的名称
local currentOutputDeviceName = hs.audiodevice.defaultOutputDevice():name()
-- 判断设备名称是否发生了变化
if lastOutputDeviceName ~= currentOutputDeviceName then
-- 判断当前设备是否为蓝牙耳机
if string.find(currentOutputDeviceName, "AirPods") then
-- 连接蓝牙耳机时将音量设置为 20
hs.audiodevice.defaultOutputDevice():setVolume(20)
hs.alert.show("音量已设为 20")
-- 判断上一个设备是否为蓝牙耳机
elseif string.find(lastOutputDeviceName, "AirPods") then
-- 断开蓝牙耳机时将音量设置为 0
hs.audiodevice.defaultOutputDevice():setVolume(0)
hs.alert.show("音量已设为 0")
end
end
-- 更新 lastOutputDeviceName 为当前设备名称
lastOutputDeviceName = currentOutputDeviceName
end

-- 为音频设备变动设置回调函数
hs.audiodevice.watcher.setCallback(handleDeviceChanges)
-- 启动音频设备监听器
hs.audiodevice.watcher.start()

4、重新加载配置。
在启动台搜索Hammerspoon,启动应用。然后在标题栏点击他的图标,然后选择Reload Config。

参考资料

https://www.v2ex.com/t/1011644