Reputation: 1048
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.
Upvotes: 1
Views: 3440
Reputation: 330
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;
}];
}
Upvotes: 2
Reputation: 5211
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];
Upvotes: 11
Reputation: 2461
To play your audio in background just add in your info.plistmake an array like this
and check it into real device not in simulator
Upvotes: 3