Play music in the background using AVAudioplayer

I had solved this question by referring iOS Application Background tasks

and make some changes in .plist file of our application..

Update

write this code in your controller's view did load method like this

- (void)viewDidLoad
{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [audioPlayer play];
    [super viewDidLoad];
}

I just wanted to add a note to Mehul's answer. This line:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

is actually very important. I used other tutorials to get my AVAudioPlayer up and running. Everything worked fine except my audio would not START if the app was in the background. To clarify, my audio was fine if it was already playing when the app went into the background...but it would not start if the app was already in the background.

Adding the above line of code made it so my audio would start even if the app was in the background.


You need to set 'audio' as one of your UIBackgroundModes in Info.plist. Apple has documentation on the issue.


Write this line in to plist for background run...

<key>UIBackgroundModes</key>
      <array>
              <string>audio</string>
      </array>

Write this code Where you want to use

AVAudioPlayer*  audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops =  1;       
[audioPlayer play];

Step1

Make the following changes in info.plist

  1. Application does not run in background : NO

  2. Required background modes

    item0 :App plays audio or streams audio/video using AirPlay

Step 2 Don't forget to add the following things in MainViewController.h file

  1. #import <'AVFoundation/AVAudioPlayer.h>
  2. @interface MainViewController:<'AVAudioPlayerDelegate>

  3. AVAudioPlayer *H_audio_player;

Step 3 Add the following code inside the play action of your MainViewController class.

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d-%d",C_CID, C_SID] ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
H_audio_player.delegate = self;
H_audio_player.numberOfLoops = -1;