首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试从后台恢复时触发了带有AVAudioSessionInterruptionWasSuspendedKey的AVAudioSessionInterruptionNotification

尝试从后台恢复时触发了带有AVAudioSessionInterruptionWasSuspendedKey的AVAudioSessionInterruptionNotification
EN

Stack Overflow用户
提问于 2019-07-25 22:13:33
回答 1查看 424关注 0票数 3

AVAudioPlayer在后台播放音频,用户可以通过耳机控制或锁定屏幕控制暂停播放。如果用户做了不到30秒,并试图恢复-一切正常。如果用户尝试在超过30秒后恢复播放-音频开始播放,但一秒钟后从AVAudioSessionDelegateaudioSessionInterruptionNotification被触发,AVAudioSessionInterruptionWasSuspendedKey是。

在此之后,应用程序将完全停止对远程控制事件的反应。正在触发事件,但AVAudioPlayer不会对任何命令做出反应。事实上,当播放继续时,[[self audioplayer] isAudioPlaying]返回NO。

如果我尝试用下面的方法来处理它-它会有帮助(所以我将AVAudioSession设置为不活动,然后playHelper方法激活它并播放音频),但有一个小故障,因为通知是在它开始播放后触发的。

代码语言:javascript
复制
- (void)audioSessionInterruptionNotification:(NSNotification *)interruption {
    UInt8 interruptionType = [[interruption.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] intValue];

    NSLog(@"Session interrupted > --- %s ---\n", interruptionType == AVAudioSessionInterruptionTypeBegan ? "Begin Interruption" : "End Interruption");
    NSDictionary *notificationUserInfo = [interruption userInfo];
    if (interruptionType == AVAudioSessionInterruptionTypeBegan) {
        if ([notificationUserInfo valueForKey:AVAudioSessionInterruptionWasSuspendedKey]) {
            [[AVAudioSession sharedInstance] setActive:false error:nil];
            [self playHelper];
        } else {
            [self interruptionStarted];
        }
    } else if (interruptionType == AVAudioSessionInterruptionTypeEnded) {
        [self interruptionEnded:(NSUInteger)[notificationUserInfo objectForKey:AVAudioSessionInterruptionOptionKey]];
    }
}

请告知可能导致此问题的原因。

EN

回答 1

Stack Overflow用户

发布于 2019-09-03 22:16:55

AVAudioSessionInterruptionWasSuspendedKey通知被抛出,因为每当你的应用程序转到后台,没有播放任何东西时,你都应该停用你的音频会话。如果您的播放器正在播放时,用户暂停从锁定屏幕,您不必停用会话。

当你的应用程序被发送到后台时,你应该监听通知,当它激活时,Swift中的代码应该如下所示。

代码语言:javascript
复制
NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { sender in
            guard self.player.isPlaying == false else { return }
            self.setSession(active: false)
        }

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { sender in
            guard self.player.isPlaying else { return }
            self.setSession(active: true)
        }

    func setSession(active: Bool) -> Bool {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(.playback, mode: .default)
            try session.setActive(active)
            return true
        } catch let error {
            print("*** Failed to activate audio session: \(error.localizedDescription)")
            return false
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57204080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档