6

I'm trying to play sequence of audio files in the background using AVAudioPlayer. When the app is not in the background it plays well, but when the app goes to the background it won't play the second song.

Here is my code:

-(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]];

}

I debugged the app and it seems that when it's about to play the second song [mainController.audioPlayer play] returns NO, which means it can't play. So what do you think?


UPDATE

After some testing it seems that it does continue to play properly only if the device locks, but if the user presses the home button and the app goes to the background the problem still remains

Alex1987
  • 9,397
  • 14
  • 70
  • 92
  • A little help for you: http://stackoverflow.com/questions/3161635/entering-background-on-ios4-to-play-audio/3161899#3161899 – iwasrobbed Jul 21 '10 at 13:14
  • Yeah I looked at that thread before, and part of my code is from there. for some reason the AVAudioPlayer refuses to play a new track when he is in the background. – Alex1987 Jul 21 '10 at 17:11
  • @IWasRobbed - It seems you had a similar issue. can you post some of your code? Thanks – Alex1987 Jul 21 '10 at 20:41
  • I have been tied up with other things so I haven't been able to work on that project. The original source of that information posted this discussion as well https://devforums.apple.com/message/239381 ..Maybe it will help you more. – iwasrobbed Jul 21 '10 at 21:06
  • Yeah I looked at that but still can't solve the problem – Alex1987 Jul 22 '10 at 20:03

1 Answers1

9

THE SOLUTION

Just add [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; and some other tweaks. It's all here

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

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Alex1987
  • 9,397
  • 14
  • 70
  • 92