Switching avaudiosession categories then retaking control of remote control center controls

后端 未结 1 569
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 06:06

This is my first post asking a question as i never usually need help but i can\'t figure out if this is even possible. What i need is to switch between these two categories of a

1条回答
  •  再見小時候
    2021-01-23 06:19

    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.

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