这就像“谷歌地图”在后台导航。
我已经将“应用程序播放音频”添加到“所需的背景模式”中,但它不起作用。它出什么问题了?
这是示例源代码:
-(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 可能来自网络,并且会在队列中播放多个音频文件。