我不确定这有多实用(我还没有机会测量CPU使用率等),但是下面的AppleScript可以完成工作-只需替换[YOUR HEADPHONES' NAME]
为耳机的实际名称即可。这是Apple支持社区线程中脚本的修改版本。
将以下脚本另存为应用程序,运行它,并将其添加到启动项中-它应在后台连续运行。
repeat
set statusOld to checkStatus()
set statusNew to checkStatus()
repeat while statusOld is equal to statusNew
delay 5 --for 5 second checks
set statusNew to checkStatus()
end repeat
if statusNew is true then
tell application "System Preferences" to activate
tell application "System Preferences"
reveal anchor "input" of pane id "com.apple.preference.sound"
end tell
delay 0.5
tell application "System Events" to tell process "System Preferences"
tell table 1 of scroll area 1 of tab group 1 of window 1
select (row 1 where value of text field 1 is "Internal Microphone")
end tell
end tell
tell application "System Preferences" to quit
else
-- Nothing needs to happen, the device was removed
end if
end repeat
on checkStatus()
set bluetoothDeviceName to "[YOUR HEADPHONES' NAME]"
set myString to do shell script "system_profiler SPBluetoothDataType"
--initial check if it's not even there
if myString does not contain bluetoothDeviceName then
return false
else
--find out if connected/disconnected
set AppleScript's text item delimiters to "name:"
set myList to the text items of myString --each item of mylist is now one of the devices
set numberOfDevices to count of myList
set counter to 1
repeat numberOfDevices times --loop through each devices checking for Connected string
if item counter of myList contains bluetoothDeviceName then
if item counter of myList contains "Connected: Yes" then
return true
else if item counter of myList contains "Connected: No" then
return false
else
display dialog "Something went wrong with the script" --this shouldn't happen
end if
end if
set counter to counter + 1
end repeat
end if
end checkStatus
您可以使用两次检查之间的时间(带有注释的行for 5 second checks
)来减少资源消耗。
AVFoundation
macOS High Sierra推出了许多新的API(尤其是中的),这些API 可以为解决此问题提供更加简洁的解决方案。如果您对Swift或Objective-C(或AppleScript和JXA中的Cocoa脚本桥)感到满意,那么在High Sierra发布后,我会考虑使用这些API代替此脚本。特别是,Apple的《音频会话编程指南》和此Stack Overflow帖子展示了一些使用来检测蓝牙连接的技术AVAudioSession
。