1

As per our requirement we need to play sound even if the app is in background. We are using [AVAudioPlayer Play] for the purpose of playing sound.

It works if the application is in foreground. But if application is in background and we are playing song in music player as well and then control goes to [AVAudioPlayer Play] statement, nothing happens.

We have already gone through many links, added the background modes in plist and have also added [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; but things did not work out.

Please suggest if there are any other alternatives.

Sagrian
  • 1,048
  • 2
  • 11
  • 29
  • possible duplicate of [AVAudioPlayer play file in Background](http://stackoverflow.com/questions/7965419/avaudioplayer-play-file-in-background) – Shubhank Feb 14 '13 at 12:14

3 Answers3

11

Just add these three lines where you initialize the AVAudioPlayer's instance:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mySong" ofType:@"mp3"]];

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

// These lines need to be added:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[audioPlayer play];
sarahhodne
  • 9,796
  • 3
  • 39
  • 44
Mohit Tomar
  • 5,173
  • 2
  • 33
  • 40
3

To play your audio in background just add in your info.plistmake an array like thisenter image description here

and check it into real device not in simulator

Sudha Tiwari
  • 2,499
  • 26
  • 50
2

Try this,

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    __block UIBackgroundTaskIdentifier task = 0;
    task=[application beginBackgroundTaskWithExpirationHandler:^{
    NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
    [application endBackgroundTask:task];
    task=UIBackgroundTaskInvalid;
    }];
}
RSM
  • 320
  • 2
  • 8