【发布时间】:2011-12-10 14:20:54
【问题描述】:
我想使用 NSTimer 通过 AVAudioPlayer 播放音乐,但 [player prepareToPlay] 返回 NO 并且不在后台播放。
有人可以给我一些想法吗?
这是我的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO];
[self.window makeKeyAndVisible];
return YES;
}
- (void)playMusic:(NSTimer *)timer{
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"];
NSURL *fileUrl = [NSURL fileURLWithPath:fileName];
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
if ([player prepareToPlay]) {
[player play];
NSLog(@"start!");
}else{
NSLog(@"error msg :%@",error);
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// /* just fail if this happens. */
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
}];
}
【问题讨论】:
标签: iphone ios4 background nstimer avaudioplayer