IOS4.0以后增加了多任务,在IOS程序退到后台之后是几种任务是可以继续执行的,比如说音乐播放,杂志下杂,location,废话不多说,现在我们以后台音乐播放为例开始我们的后台模式。
1.编辑plist,设置我们需要的后台模式,其次添加我们的音乐文件
从上图中可以清楚的看到,我添加的音乐文件是hello.mp3,然后我在info.plist中设置的后台模式有3种,这是为了让大家一目了然,其实我们只用到第一种,后台播放音频文件的设置。
2.在进入到后台模式的回调函数中调用声音播放的函数
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSError *error;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:&error];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Hello" ofType:@"mp3"];
BOOL fileExit = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExit) {
_player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:filePath ] error:nil ];
[_player prepareToPlay];
}
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[[com_gamewaveViewController alloc] initWithNibName:@"com_gamewaveViewController_iPhone" bundle:nil] autorelease];
} else {
self.viewController = [[[com_gamewaveViewController alloc] initWithNibName:@"com_gamewaveViewController_iPad" bundle:nil] autorelease];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
上面的代码中,[session setCategory :AVAudioSessionCategoryPlayback error :&error];这一行是表明我要后台继续播放这个文件
3,代码编译通过,运行,通过!