Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone: playing audio playlist in the background?

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

like image 728
Alex1987 Avatar asked Jul 21 '10 08:07

Alex1987


People also ask

Why is my iPhone playing music in the background?

In most cases, the reason the iPhone plays music on its own is the Music app on the device. It doesn't matter if you are using any third-party app or Apple's native music app, it can keep running in the background. Therefore, you would have to close the app manually to make sure it won't keep playing by itself.

How do I turn off background music on my iPhone?

The only way to stop the music on an iPhone is to tap on the Pause button and then on the Home button to return to the Home screen. The music app will keep running in the background and after some period of inactivity, iOS will automatically close it.


1 Answers

THE SOLUTION

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

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

like image 105
Alex1987 Avatar answered Sep 19 '22 11:09

Alex1987