objective c audio meter

前端 未结 1 1713
礼貌的吻别
礼貌的吻别 2021-01-03 15:55

Is it possible for xcode to have an audio level indicator?

I want to do something like this:

if (audioLevel = 100) {
}

or somethin

相关标签:
1条回答
  • 2021-01-03 16:33

    Unfortunately, there isn't a very straightforward API to do this. You need to use the low level AudioToolbox.framework.

    Luckily, others have already solved this problem for you. Here's some code I simplified slightly to be straight C functions, from CocoaDev. You need to link to the AudioToolbox to compile this code (see here for documentation on how to do so).

    #import <AudioToolbox/AudioServices.h>
    
    AudioDeviceID getDefaultOutputDeviceID()
    {
        AudioDeviceID outputDeviceID = kAudioObjectUnknown;
    
        // get output device device
        OSStatus status = noErr;
        AudioObjectPropertyAddress propertyAOPA;
        propertyAOPA.mScope = kAudioObjectPropertyScopeGlobal;
        propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
        propertyAOPA.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
    
        if (!AudioHardwareServiceHasProperty(kAudioObjectSystemObject, &propertyAOPA))
        {
            printf("Cannot find default output device!");
            return outputDeviceID;
        }
    
        status = AudioHardwareServiceGetPropertyData(kAudioObjectSystemObject, &propertyAOPA, 0, NULL, (UInt32[]){sizeof(AudioDeviceID)}, &outputDeviceID);
    
        if (status != 0) 
        {
            printf("Cannot find default output device!");
        }
        return outputDeviceID;
    }
    
    float getVolume () 
    {
        Float32 outputVolume;
    
        OSStatus status = noErr;
        AudioObjectPropertyAddress propertyAOPA;
        propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
        propertyAOPA.mSelector = kAudioHardwareServiceDeviceProperty_VirtualMasterVolume;
        propertyAOPA.mScope = kAudioDevicePropertyScopeOutput;
    
        AudioDeviceID outputDeviceID = getDefaultOutputDeviceID();
    
        if (outputDeviceID == kAudioObjectUnknown)
        {
            printf("Unknown device");
            return 0.0;
        }
    
        if (!AudioHardwareServiceHasProperty(outputDeviceID, &propertyAOPA))
        {
            printf("No volume returned for device 0x%0x", outputDeviceID);
            return 0.0;
        }
    
        status = AudioHardwareServiceGetPropertyData(outputDeviceID, &propertyAOPA, 0, NULL, (UInt32[]){sizeof(Float32)}, &outputVolume);
    
        if (status)
        {
            printf("No volume returned for device 0x%0x", outputDeviceID);
            return 0.0;
        }
    
        if (outputVolume < 0.0 || outputVolume > 1.0) return 0.0;
    
        return outputVolume;
    }
    
    int main (int argc, char const *argv[])
    {
        printf("%f", getVolume());
        return 0;
    }
    

    Note that there's also a setVolume function there, too.

    0 讨论(0)
提交回复
热议问题