I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.
I had used following code:-
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach" ofType: @"mp3"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; NSError *error; playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error]; playerTemp.numberOfLoops = 0; AudioSessionSetActive(true); [playerTemp play];
Go to Settings > Accessibility > Audio/Visual > Background Sounds, then turn on Background Sounds. Set any of the following: Sound: Choose a sound; the audio file downloads to your iPhone.
Turn on Background SoundsTap Background Sounds to turn it on. Tap the name of the current sound to view other sounds, then tap a sound name to listen to a preview. After you choose a sound, tap outside of the card to go back.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With