(已为Swift 4和更高版本更新了代码,可以在编辑历史记录中找到Swift 2和3版本。)
这是从将 10.6(雪豹)以编程方 转换为OSX系统卷并以编程方式将Mac OSX卷设置为Swift(为简洁起见,省略错误检查)的答案得到的:
所需框架:
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.0var 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)
为简便起见,已省略了错误检查。当然,应该在实际应用程序中检查状态返回值是否成功。
积分去 设置OS X量OS X 10.11雨燕采用不使用过时的AudioHardwareServiceSetPropertyDataAPI 的使用
AudioObjectSetPropertyData(),而不是过时的
AudioHardwareServiceSetPropertyData()。
正如noamtm在评论中提到的那样,这也可以通过传递以下内容来获取和设置左右平衡
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterBalance
到
AudioObjectPropertyAddress()。



