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/

相关文章:

objective-c - 错误的值被复制到TPCircularBuffer

iphone - 在 iPhone 模拟器上调用 AudioUnit 渲染回调,但在手机上不调用

ios - 使用来自原始 PCM 16000 采样率流的 CMSampleTimingInfo、CMSampleBuffer 和 AudioBufferList

objective-c - 更改 MAC 地址 Cocoa - Objective-C

iOS:在用户向下拖动时拉伸(stretch)/调整 UITableView 标题?

iOS UInt64 数字 float 错误

macos - Mac : reloading document in Chrome or Firefox?

python - 如何使 PsychoPy 对象保持 Visual.Window 成为 Windows 7 上最顶层(事件)窗口?

objective-c - 速记选择器调用

c - 将文件写入 "DiagnosticReports"时访问被拒绝