0
这就像“Google地图”在后台导航一样。当应用程序进入后台时开始播放音频文件
我已经将“应用程序播放音频”添加到“所需的背景模式”,但它不起作用。 它有什么问题?
下面是示例代码:
-(void)applicationDidEnterBackground:(UIApplication *)application
{
UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
{
backgroundSupported = device.multitaskingSupported;
}
if (backgroundSupported && _bgTask==UIBackgroundTaskInvalid)
{
UIApplication* app = [UIApplication sharedApplication];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (app.applicationState==UIApplicationStateBackground && _bgTask!=UIBackgroundTaskInvalid)
{
[NSThread sleepForTimeInterval:3];
[self playAudio];
}
[app endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
});
}
}
-(void)playAudio {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"caf"];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
[self.audioPlayer setNumberOfLoops:-1];
self.audioPlayer.delegate = self;
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
}
音频文件的URL可能是从网络,并会在队列中播放多种音频文件。
你可以尝试删除行[self.audioPlayer prepareToPlay];并再试一次?如果您尝试调试并且如果调用playAudio方法,您是否也可以让我们知道... – Prav 2013-04-25 11:14:14
删除[self.audioPlayer prepareToPlay]后仍然无法工作;为什么要删除它? – al03 2013-04-26 06:21:32