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