StackOverflow上有很多关于iOS背景音乐播放的问题.没有完全探索所有边缘情况,这个问题的目的是成为iOS背景音频问题的最后一个词
所有代码,问题和示例均参考ios5.
"背景" - 当用户按下主页按钮或电源按钮时应用程序的状态(因此设备显示锁定屏幕).该应用程序还可以使用多任务切换器或iPad上的多任务手势进入后台.
"audio" - 使用AudioQueue播放的音频(包括AVAudioPlayer)
据我了解,有一个要求让应用程序在后台播放音频.
UIBackgroundModes于audio在Info.plist[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];我的用例是在后台播放相对较长的音频(音乐).可能有数百个曲目,应用程序将按顺序播放它们.可以认为音频将无限播放.
该应用程序将通过暂停播放来处理中断.
我的成功喜忧参半:
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:...];
Run Code Online (Sandbox Code Playgroud)
允许音频在后台播放.但是我很困惑它是否需要以及它与以下内容的区别:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Run Code Online (Sandbox Code Playgroud)
中断.如果您注册成为音频中断(电话等)的通知,则成为其代表AVAudioPlayer.例如,如果您在中断开始时暂停或停止音频,则在结束时恢复,如果中断超过10分钟(后台任务完成的最长时间),您的应用程序将被暂停?
如果调用Lock或Home,模拟器将停止音频,同时使用:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Run Code Online (Sandbox Code Playgroud)但是这适用于设备.这是一个已知的问题?
我成功启用了我的应用程序,以便在屏幕锁定后能够在后台播放音频和视频.但是,为了获得更好的用户体验,我想在锁定的屏幕上显示正在运行的媒体的播放和暂停控制.在线关注几个博客后,添加了以下代码:
@interface MyControllerClass () <UIGestureRecognizerDelegate, UIApplicationDelegate>
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *activationError = nil;
BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
}
- (void)viewWillDisappear:(BOOL)animated {
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (BOOL) canBecomeFirstResponder {
return YES;
}
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
NSLog(@"received event %@",receivedEvent);
if (receivedEvent.type == …Run Code Online (Sandbox Code Playgroud)