2013-04-25 85 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第一行代碼加時的經驗,否則系統暫停前的應用音頻有機會踢入並保持清醒。

相關問題