Macos 使用Swift的AudioToolbox访问OS X主卷
在我的Swift应用程序中是否有设置系统主音量的解决方案 我阅读了很多关于AudioToolbox的内容,并阅读了Objective-C中的一些源代码示例。例如,我发现: 但我不能用斯威夫特 我在中缺少一些示例代码(为Swift 4和更高版本更新的代码,可以在编辑历史记录中找到Swift 2和3版本。) 这是我从将答案翻译成Swift(为简洁起见省略了错误检查)中得到的: 所需框架:Macos 使用Swift的AudioToolbox访问OS X主卷,macos,cocoa,swift,audiotoolbox,Macos,Cocoa,Swift,Audiotoolbox,在我的Swift应用程序中是否有设置系统主音量的解决方案 我阅读了很多关于AudioToolbox的内容,并阅读了Objective-C中的一些源代码示例。例如,我发现: 但我不能用斯威夫特 我在中缺少一些示例代码(为Swift 4和更高版本更新的代码,可以在编辑历史记录中找到Swift 2和3版本。) 这是我从将答案翻译成Swift(为简洁起见省略了错误检查)中得到的: 所需框架: import AudioToolbox 获取默认输出设备: var defaultOutputDeviceID
import AudioToolbox
获取默认输出设备:
var defaultOutputDeviceID = AudioDeviceID(0)
var defaultOutputDeviceIDSize = UInt32(MemoryLayout.size(ofValue: defaultOutputDeviceID))
var getDefaultOutputDevicePropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: AudioObjectPropertyElement(kAudioObjectPropertyElementMaster))
let status1 = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&getDefaultOutputDevicePropertyAddress,
0,
nil,
&defaultOutputDeviceIDSize,
&defaultOutputDeviceID)
设置音量:
var volume = Float32(0.50) // 0.0 ... 1.0
var volumeSize = UInt32(MemoryLayout.size(ofValue: volume))
var volumePropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
mScope: kAudioDevicePropertyScopeOutput,
mElement: kAudioObjectPropertyElementMaster)
let status2 = AudioObjectSetPropertyData(
defaultOutputDeviceID,
&volumePropertyAddress,
0,
nil,
volumeSize,
&volume)
最后,为了完整起见,获取卷:
var volume = Float32(0.0)
var volumeSize = UInt32(MemoryLayout.size(ofValue: volume))
var volumePropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
mScope: kAudioDevicePropertyScopeOutput,
mElement: kAudioObjectPropertyElementMaster)
let status3 = AudioObjectGetPropertyData(
defaultOutputDeviceID,
&volumePropertyAddress,
0,
nil,
&volumeSize,
&volume)
print(volume)
为简洁起见,省略了错误检查。当然,在实际应用程序中,应该检查状态返回值是否成功
使用AudioObjectSetPropertyData()
而不是弃用的AudioHardwareServiceSetPropertyData()
正如评论中提到的,这也可以通过传递来获得和设置左右平衡
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterBalance
到
AudioObjectPropertyAddress()
酷。谢谢。现在我看到了我在AudioDeviceId和kAudio上犯的错误……在Swift 5中,您还需要导入CoreAudio
,并且kAudio
属性的类型正确。@zneak:谢谢您让我知道。我已经更新了Swift 4(和5)的代码。在我的项目中,导入AudioToolbox就足够了,即使是在Swift 5(Xcode 10.2 beta版)中也是如此。在Catalina 10.15.2、Swift 5、Xcode 11.3.1中工作得非常好。我想补充的是,左右平衡也可以通过相同的方式进行控制,只需将kAudioHardwareServiceDeviceProperty\u VirtualMasterVolume
更改为kAudioHardwareServiceDeviceProperty\u VirtualMasterBalance
@请考虑把这张便条加在答案上。