开发者

objective c audio meter

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

I want to do something like this:开发者_Go百科

if (audioLevel = 100) {
}

or something similar...

Any ideas?? Example code please?

I'm VERY new to objective c so the more explaining the beter! :D


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜