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];
I use the below code. It work for me, and call on the button click of audio player instance method.
Step1
Make the following changes in info.plist
Application does not run in background : NO
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#import <'AVFoundation/AVAudioPlayer.h>
@interface MainViewController:<'AVAudioPlayerDelegate>
AVAudioPlayer *H_audio_player;
Step 3 Add the following code inside the play action of your
MainViewController
class.From all answers is missing this code to control the player when user is waking the device:
And you have all these options:
If even after setting audio as one of your
UIBackgroundModes
in the plist the audio stops when going to background, trysetting
yourapplication's audio session
tomedia playback
.Here's the related reference: https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html
Here's about what the code's gonna look like:
To play your audio in background
Step 1 :Just add in your info.plistmake an array
step2 :
step3 :
From Apple's sample code: Audio Mixer (MixerHost)
I think remote control events are not needed for the following case: