首页 文章

iphone:在后台播放音频播放列表?

提问于
浏览
6

我正在尝试使用AVAudioPlayer在后台播放音频文件序列 . 当应用程序不在后台时,它可以很好地播放,但当应用程序进入后台时,它将无法播放第二首歌曲 .

这是我的代码:

-(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 play]时返回NO,这意味着它无法播放 . 所以你怎么看?


UPDATE

经过一些测试后,它似乎只有在设备锁定时才会继续正常播放,但如果用户按下主页按钮并且应用程序进入后台,问题仍然存在

1 回答

  • 9

    解决方案

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

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

相关问题