我想使用NSTimer与AVAudioPlayer一起播放音乐,但[player prepareToPlay]
返回NO &不在后台播放。AVAudioPlayer不能在后台使用NSTimer播放音乐
有人可以给我一些想法吗?
这里是我的代码:
- (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];
}];
}
我在plist.info中添加了密钥,但它仍然无法播放... – Garen
但是当我在应用程序中启动音乐时,它可以在后台播放... 令我疯狂很久.. 。> _ < – Garen