footyapps27
footyapps27

Reputation: 4042

AVAudioPlayer does not play when app goes to background

I am trying out the AVFoundationFramework.

Presently I am able to run the AVAudioPlayer in the foreground. When the app goes to the background, the AVAudioPlayer does not continue to play.

The exact steps of implementation are:

  1. Adding Background Tasks to the .plist

    enter image description here

  2. Setting up AVAudioPlayer

    self.objAVAudioPlayer = [[AVAudioPlayer alloc]initWithData:mp3Data error:&error];
    self.objAVAudioPlayer.delegate = self;
    
  3. Setting up AVAudioSession

    if([self.objAVAudioPlayer prepareToPlay])
    {
        AVAudioSession *objAVAudioSession = [AVAudioSession sharedInstance];
        [objAVAudioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
        [objAVAudioSession setActive:YES
                                         error:nil];
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self.objAVAudioPlayer play];
    }
    

When the app is resumed, it starts from the exact same place where it resigned.

The base SDK is iOS 7.0.

Any idea as to what I am missing? Any help will be appreciated.

Upvotes: 3

Views: 1006

Answers (1)

Mithgollor
Mithgollor

Reputation: 61

For playing audio in background mode you should set up AVAudioSession and add this code

UIBackgroundTaskIdentifier backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
    [application endBackgroundTask:backgroundTask]; //Tell the system that we are done with the tasks
    backgroundTask = UIBackgroundTaskInvalid; //Set the task to be invalid
 }];

into your AppDelegate.m class in method

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //Some code
}

Upvotes: 1

Related Questions