mac设置系统扬声器 objective-c c++

//依赖库

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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值