2010-07-21 132 views
6

我想用AVAudioPlayer在后台播放音频文件的序列。当应用程序不在背景中时,播放效果很好,但当应用程序转到背景时,它不会播放第二首歌曲。iphone:在后台播放音频播放列表?

这里是我的代码:

-(void)playAudio:(NSString *)path{ 
    NSURL *url = [NSURL fileURLWithPath:path]; 

    NSError *error; 
    AVAudioPlayer *ap = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error: nil]; 
    ap.delegate = self; 

    mainController.audioPlayer = ap; 
    [ap release]; 


    if (mainController.audioPlayer == nil) 
     NSLog([error description]); 
    else{ 


     UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid; 

     [mainController.audioPlayer prepareToPlay]; 

     if([mainController.audioPlayer play]){ 

      newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; 

     } 

     if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid) 
      [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; 

     bgTaskId = newTaskId; 
    } 

} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{ 
    NSLog(@"finished now next..."); 
    [self playAudio:[self getNextAudio]]; 

} 

我调试的应用程序,它似乎是当它即将播放的第二首歌[mainController.audioPlayer播放]返回NO,这意味着它不能播放。 那你觉得呢?


UPDATE

一些测试后,它似乎并继续正常播放只有当设备锁,但如果用户按下home键和应用程序转到后台问题仍然存在

+0

一点帮助你:http://stackoverflow.com/questions/3161635/entering-background-on-ios4-to-play-audio/3161899#3161899 – iwasrobbed 2010-07-21 13:14:58

+0

是的,我看了在那个线程之前,我的代码的一部分是从那里。出于某种原因,AVAudioPlayer拒绝在背景中播放新曲目。 – Alex1987 2010-07-21 17:11:25

+0

@IWasRobbed - 看起来你有类似的问题。你可以发布一些你的代码吗?谢谢 – Alex1987 2010-07-21 20:41:21

回答

9

解决方案

只需添加[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];和其他一些调整。这一切都在这里

https://devforums.apple.com/message/264397

+0

绝对救生员!我一直在这个谷歌搜索了一天半:) – kritzikratzi 2012-07-19 16:46:24

+0

链接到解释是打破 – Shaybc 2016-04-14 20:27:20