应用程序重新激活后,AVAudioSession无法播放声音

bel*_*nta 3 core-audio ios avaudiosession

所以我有一个音乐应用程序使用AVAudioSession允许它在后台播放.我用这个电话:

[audioSession setActive:YES
            withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                  error:nil];
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,如果我去另一个应用程序,它窃取音频会话(因此现在停止从我的应用程序播放音乐和播放其他东西),我回到我的应用程序,无论我做什么重置我的音频会话或我的音频单元,我的应用程序的声音消失了.

有谁知道该怎么办?

mar*_*aie 5

因此,在注册AVAudioSession通知后:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleAudioSessionInterruption:)
                                             name:AVAudioSessionInterruptionNotification
                                           object:aSession]; 
Run Code Online (Sandbox Code Playgroud)

你需要恢复/重启你需要在处理程序中断类型重启你的播放器是AVAudioSessionInterruptionTypeEnded:

- (void)handleAudioSessionInterruption:(NSNotification*)notification {

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
            // • Audio has stopped, already inactive
            // • Change state of UI, etc., to reflect non-playing state
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [player play];
            }
        } break;
        default:
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到一个完整的解释:AVplayer在来电后恢复