我正在尝试使用 AVAudioPlayer 在后台播放音频文件序列.当应用程序不在后台时它播放得很好,但是当应用程序进入后台时它不会播放第二首歌曲.
I'm trying to play sequence of audio files in the background using AVAudioPlayer. When the app is not in the background it plays well, but when the app goes to the background it won't play the second song.
这是我的代码:
-(void)playAudio:(NSString *)path{ NSURL *url = [NSURL fileURLWithPath:path]; NSError *error; AVAudioPlayer *ap = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; ap.delegate = self; mainController.audioPlayer = ap; [ap release]; if (mainController.audioPlayer == nil) NSLog([error description]); else{ UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid; [mainController.audioPlayer prepareToPlay]; if([mainController.audioPlayer play]){ newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; } if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; bgTaskId = newTaskId; } } - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ NSLog(@"finished now next..."); [self playAudio:[self getNextAudio]]; }我调试了应用程序,似乎在要播放第二首歌曲时[mainController.audioPlayer play] 返回NO,这意味着它无法播放.那你怎么看?
I debugged the app and it seems that when it's about to play the second song [mainController.audioPlayer play] returns NO, which means it can't play. So what do you think?
更新
经过一些测试,似乎只有在设备锁定时它才能继续正常播放,但是如果用户按下主页按钮并且应用程序进入后台,问题仍然存在
After some testing it seems that it does continue to play properly only if the device locks, but if the user presses the home button and the app goes to the background the problem still remains
推荐答案THE SOLUTION
THE SOLUTION
只需添加 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 和其他一些调整.都在这里
Just add [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; and some other tweaks. It's all here
devforums.apple/message/264397
更多推荐
iphone:在后台播放音频播放列表?
发布评论