Switching avaudiosession categories then retaking control of remote control center controls

三世轮回 提交于 2019-12-02 02:32:43

I've found a solution that works for me, which involves calling

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]

or

[[UIApplication sharedApplication] endReceivingRemoteControlEvents]

before setting AVAudioSession category options. eg:

NSUInteger options = ... // determine your options

// it seems that calls to beginReceivingRemoteControlEvents and endReceivingRemoteControlEvents
// need to be balanced, so we keep track of the current state in _isReceivingRemoteControlEvents

BOOL shouldBeReceivingRemoteControlEvents = ( 0 == (options & AVAudioSessionCategoryOptionMixWithOthers) );

if(_isReceivingRemoteControlEvents != shouldBeReceivingRemoteControlEvents) {
    if(shouldBeReceivingRemoteControlEvents) {
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        _isReceivingRemoteControlEvents=YES;
    } else {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        _isReceivingRemoteControlEvents=NO;
    }
}

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:options error:&error];

...

[[AVAudioSession sharedInstance] setActive:YES error:&error]

I've been able to achieve consistent results by using a variable to keep track of whether or not the app is currently receiving remote control events so that I can ensure that calls to (begin/end)ReceivingRemoteControlEvents are balanced. I haven't found any documentation that says that you need to do this but otherwise things don't always seem to behave as expected, particularly since I call this code multiple times throughout the course of the application.

In my implementation, the code above gets called each time the app comes to the foreground and also just before each time I begin playing audio.

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!