2013-04-25 62 views
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可能是从网络,并会在队列中播放多种音频文件。

+0

你可以尝试删除行[self.audioPlayer prepareToPlay];并再试一次?如果您尝试调试并且如果调用playAudio方法,您是否也可以让我们知道... – Prav 2013-04-25 11:14:14

+0

删除[self.audioPlayer prepareToPlay]后仍然无法工作;为什么要删除它? – al03 2013-04-26 06:21:32

回答

0

Apple's doc on the subject

因为很可能你在 applicationDidEnterBackground启动任何后台任务:将不运行,直到方法 退出后,你应该 之前请求额外的后台执行时间启动这些任务。换句话说,首先调用 beginBackgroundTaskWithExpirationHandler:然后在 调度队列或辅助线程上运行任务。

从我自己的播放背景声音,如果你不要求你需要事先设置的东西,使[self.audioPlayer play]是字面上的applicationDidEnterBackground第一行代码加时的经验,否则系统暂停前的应用音频有机会踢入并保持清醒。

相关问题