我想使用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