//依赖库
LIBS += -framework CoreAudio
//头文件
#include <CoreAudio/CoreAudio.h>
#include <string>
//代码
bool isOutputDevice(AudioDeviceID deviceID)
{
UInt32 propertySize = 256;
// if there are any output streams, then it is an output
AudioDeviceGetPropertyInfo(deviceID, 0, false, kAudioDevicePropertyStreams, &propertySize, NULL);
if (propertySize > 0)
return true;
return false;
}
void getDeviceName(AudioDeviceID deviceID, char * deviceName)
{
UInt32 propertySize = 256;
AudioDeviceGetProperty(deviceID, 0, false, kAudioDevicePropertyDeviceName, &propertySize, deviceName);
}
AudioDeviceID getDeviceID(const std::string &deviceName)
{
UInt32 propertySize;
AudioDeviceID dev_array[64];
int numberOfDevices = 0;
char tmpdeviceName[256];
AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propertySize, dev_array);
numberOfDevices = (propertySize / sizeof(AudioDeviceID));
for(int i = 0; i < numberOfDevices; ++i)
{
if (isOutputDevice(dev_array[i]))
{
getDeviceName(dev_array[i], tmpdeviceName);
if (deviceName == std::string(tmpdeviceName))
return dev_array[i];
}
}
return kAudioDeviceUnknown;
}
/*
* 设置系统扬声器
* deviceName:扬声器名称
* return:成功/失败
*/
bool setSystemSpeaker(const std::string &deviceName)
{
if (deviceName.empty())
{
return false;
}
AudioDeviceID newDeviceID = getDeviceID(deviceName);
if (kAudioDeviceUnknown == newDeviceID)//device id is unknown
{
return false;
}
UInt32 propertySize = sizeof(UInt32);
OSStatus status = AudioHardwareSetProperty(kAudioHardwarePropertyDefaultOutputDevice, propertySize, &newDeviceID);
return noErr==status ? true : false;
}