I have done a lot of research, both on Google and StackOverflow. All the answers I found do not work in iOS 7. I started writing fresh app in iOS 7 SDK with Xcode 5.
All
If you want to play audio in background in iphone and simulator also then you need to write this code in plist and Firstly make sure your Info.plist correctly lists audio as a background mode.
(If you dont know what i'm talking about select YOURAPPNAME-Info.plist select that. Click on the plus sign and type a key UIBackgroundModes and enter. Add a value called "App plays audio"(for simulator) or "App plays audio or streams audio/video using AirPlay"(For iphone).)
in 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;
}];
}
Add these two framework in your project and some line of code in ViewController.h
#import
#import
@interface ViewController : UIViewController
@property (nonatomic) MPMoviePlayerController *audioPlayer;
Remind that these frameworks refrences should be added in your project.
Then in Viewcontrller.m
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.audioPlayer stop];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *audioUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"songName" ofType:@"mp3"]];
self.audioPlayer = [[MPMoviePlayerController alloc] initWithContentURL:audioUrl];
[self.audioPlayer prepareToPlay];
[self.audioPlayer.view setFrame:CGRectMake(0, 0, self.view.frame.size.width-100, 42)];
self.audioPlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.audioPlayer.view];
[self.audioPlayer play];
// for run application in background
NSError *setCategoryError = nil;
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive:YES error:&activationError];
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
}
I hope it will help you to play audio in background in iphone and simulator as well.