方式一
- (void)applicationDidEnterBackground:(UIApplication *)application {
_backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:_backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}];
}
在后臺(tái)開(kāi)啟一個(gè)新的long-run的任務(wù),一般只有10分鐘,10分鐘以后自動(dòng)調(diào)用Block里面的方法,結(jié)束這個(gè)后臺(tái)任務(wù),否則,系統(tǒng)會(huì)殺死這個(gè)APP,或者手動(dòng)調(diào)用Block里面的內(nèi)容,結(jié)束這個(gè)后臺(tái)任務(wù)
方式二
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"wusheng" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
if (self.audioPlayer != nil){
self.audioPlayer.delegate = self;
[self.audioPlayer setNumberOfLoops:-1];
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing...");
} else {
NSLog(@"Failed to play.");
}
} else {
}
});
步驟
- 在info.plist中添加Required background modes悬襟。并設(shè)置為:audio
- 初始化一個(gè)AVAudioPlayer音頻缭黔,并且無(wú)限制的播放下去矾柜。
參考[資料]
[資料]: http://blog.sina.com.cn/s/blog_7b9d64af0101cjci.html