objective-c - 如何获得 Mac 音频电平?

标签 objective-c macos core-audio audiotoolbox

目前,我的代码可以成功返回用户可以使用音量键设置的系统音频值。

但是,我想要的是扬声器播放的音频值。因此,如果用户正在观看 Netflix 并且某个角色开始尖叫,则返回的值会高于该角色在窃窃私语时的值。

我现在的代码:

+ (AudioDeviceID)defaultOutputDeviceID {
    OSStatus status = noErr;

    AudioDeviceID outputDeviceID = kAudioObjectUnknown;

    AudioObjectPropertyAddress propertyAOPA;
    propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
    propertyAOPA.mScope = kAudioObjectPropertyScopeGlobal;
    propertyAOPA.mSelector = kAudioHardwarePropertyDefaultSystemOutputDevice;

    UInt32 propertySize = sizeof(outputDeviceID);

    if (!AudioHardwareServiceHasProperty(kAudioObjectSystemObject, &propertyAOPA)) {
        NSLog(@"Cannot find default output device!");
        return outputDeviceID;
    }

    status = AudioHardwareServiceGetPropertyData(kAudioObjectSystemObject, &propertyAOPA, 0, NULL, &propertySize, &outputDeviceID);

    if(status) {
        NSLog(@"Cannot find default output device!");
    }

    return outputDeviceID;
}

+ (float)volume {
    OSStatus status = noErr;

    AudioDeviceID outputDeviceID = [[self class] defaultOutputDeviceID];

    if (outputDeviceID == kAudioObjectUnknown) {
        NSLog(@"Unknown device");
        return 0.0;
    }

    AudioObjectPropertyAddress propertyAOPA;
    propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
    propertyAOPA.mScope = kAudioDevicePropertyScopeOutput;
    propertyAOPA.mSelector = kAudioHardwareServiceDeviceProperty_VirtualMasterVolume;

    Float32 outputVolume;
    UInt32 propertySize = sizeof(outputVolume);

    if (!AudioHardwareServiceHasProperty(outputDeviceID, &propertyAOPA)) {
        NSLog(@"No volume returned for device 0x%0x", outputDeviceID);
        return 0.0;
    }

    status = AudioHardwareServiceGetPropertyData(outputDeviceID, &propertyAOPA, 0, NULL, &propertySize, &outputVolume);

    if (status) {
        NSLog(@"No volume returned for device 0x%0x", outputDeviceID);
        return 0.0;
    }

    if (outputVolume < 0.0 || outputVolume > 1.0)
        return 0.0;

    return outputVolume;
}

最佳答案

获取音量级别并根据需要进行设置(作为最大音量),然后再次将其恢复为用户的原始音量级别。有关详细信息,您可以查看以下链接; https://stackoverflow.com/a/27743599/1351327
希望它会有所帮助。 (小心苹果会拒绝你的应用)

关于objective-c - 如何获得 Mac 音频电平?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466338/

相关文章:

ios - 为特定 ASBD 缓冲区获取正确的数字数据类型转换

xcode - 核心音频SDK,Xcode 5.1

iphone - Objective-C 中不常用的符号

cocoa - 来自 AXUIElement 的 CGWindowID

javascript - 如何以编程方式设置 WebKit 密码文本字段的值?

linux - 是否有任何类 Unix 系统将含义赋予目录上的 SUID 位?

ios - 使用Core Audio获取麦克风输入和扬声器输出

objective-c - 使用 ARC 时重新分配属性

ios - 具有自定义逻辑的可重用 UITableViewCell

objective-c - 在基于文档的应用程序中使用最前面窗口的控件?