AVAudioPlayer在后台播放音频,用户可以通过耳机控制或锁定屏幕控制暂停播放。如果用户做了不到30秒,并试图恢复-一切正常。如果用户尝试在超过30秒后恢复播放-音频开始播放,但一秒钟后从AVAudioSessionDelegate的audioSessionInterruptionNotification被触发,AVAudioSessionInterruptionWasSuspendedKey是。
在此之后,应用程序将完全停止对远程控制事件的反应。正在触发事件,但AVAudioPlayer不会对任何命令做出反应。事实上,当播放继续时,[[self audioplayer] isAudioPlaying]返回NO。
如果我尝试用下面的方法来处理它-它会有帮助(所以我将AVAudioSession设置为不活动,然后playHelper方法激活它并播放音频),但有一个小故障,因为通知是在它开始播放后触发的。
- (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]];
}
}请告知可能导致此问题的原因。
发布于 2019-09-03 22:16:55
AVAudioSessionInterruptionWasSuspendedKey通知被抛出,因为每当你的应用程序转到后台,没有播放任何东西时,你都应该停用你的音频会话。如果您的播放器正在播放时,用户暂停从锁定屏幕,您不必停用会话。
当你的应用程序被发送到后台时,你应该监听通知,当它激活时,Swift中的代码应该如下所示。
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
}
}https://stackoverflow.com/questions/57204080
复制相似问题