我实际上正在开发一个根据用户位置播放录音的应用。我在尝试在后台使用该应用程序时遇到了一些问题。我已启用后台模式在后台播放音频,它在模拟器中运行良好。问题是,当我在背景中使用app调用我的autoplayRecord方法时,它不会播放任何记录。这是我的代码:
- (void) autoplayRecord
{
autoplayingRecord = [_autoplayList objectAtIndex:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
loadingSong = YES;
dispatch_async(dispatch_get_main_queue(), ^{
[self showTitle:autoplayingRecord.title];
[audioPlayer stop];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
});
NSError *error;
NSData *songFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:autoplayingRecord.audioURL] options:NSDataReadingMappedIfSafe error:&error];
audioPlayer = [[AVAudioPlayer alloc] initWithData:songFile error:&error];
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
loadingSong = NO;
if (audioPlayer == nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicatorView stopAnimating];
[self stopRecord];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicatorView stopAnimating];
[audioPlayer play];
});
}
});
}