开发者

AVAudioSession category not working as documentation dictates

开发者 https://www.devze.com 2023-02-22 14:17 出处:网络
I have an iOS app that has some audio feedback in certain places, but I want any other music the user has playing in the background to be allowed to play over this. In addition, I want the audio in my

I have an iOS app that has some audio feedback in certain places, but I want any other music the user has playing in the background to be allowed to play over this. In addition, I want the audio in my app to respect the mute switch. According to the developer documentation, this functionality should all be enabled by the AVAudioSession ambient category. This is the code I'm using:

if (!hasInitialisedAudioSession) {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryAmbient error:NULL];

    [ses开发者_Go百科sion setActive:YES error:NULL];

    hasInitialisedAudioSession = YES;
}

The code is executing just fine, and it does indeed let the app sounds play over iPod music. What it doesn't do, however, is respect the mute switch. I've tried swapping this code out for similar C audio calls (stuff like AudioSessionSetProperty) instead of the Objective-C calls, but I get the same result - the ambient session category simply doesn't want to respect the mute switch, despite what the documentation says it should be doing.

Any ideas? Thanks for the help :)


I think I managed to work it out - turns out that it has nothing to do with my app at all, but rather the iPod app. My app obeys the mute switch as it should when the iPod isn't playing, and then allows the iPod to play over it - all behaviour I wanted. However, when the iPod is playing, the app stops responding to the mute switch, so I think it's just something the iPod does to the device audio settings. I could probably work a way around it if I really wanted to spend the time on it, but as long as it obeys the mute switch when the iPod isn't playing that's good enough for me.

EDIT: to work around this, just use this function to determine whether or not the mute switch is on manually, and don't play your sounds if the result is YES. Could be a bit of a pain if you don't have a central audio manager class, though. It would be nice if Apple could publish this behaviour in their documentation.

- (BOOL)deviceIsSilenced
{
    #if TARGET_IPHONE_SIMULATOR
    // return NO in simulator. Code causes crashes for some reason.
    return NO;
    #endif

    CFStringRef state;
    UInt32 propertySize = sizeof(CFStringRef);
    AudioSessionInitialize(NULL, NULL, NULL, NULL);
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);

    return (CFStringGetLength(state) <= 0);
}
0

精彩评论

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

关注公众号