You need to do this init in viewDidLoad :
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath]; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil];
This is to initialize the audio. Here, with an MP3 test with a name imported into the project. Note that the beginReceivingRemoteControlEvents part is very important. Without it, you canโt start playing from the stage, just keep listening to music already playing from the foreground.
Now you need to listen to the didEnterInBackGround event (you can go with the applicationDidEnterBackground of your application delegate, but in this way you can put the code in the it belongs class):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBG:) name:UIApplicationDidEnterBackgroundNotification object:nil];
And now in this didEnterBG :
self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES]; [self.backgroundTimer fire];
Here I repeat this sound every 10 seconds for personal reasons, but I do everything you need. Finally, the backgroundWork method:
- (void)backgroundWork{ [self.audioPlayer prepareToPlay]; [self.audioPlayer play]; }
Now your background file is playing in the background :-)
It should also be noted that your application must have certain rights to perform tasks in the background. You must check the box under "YourTarget" โ Features โ Background Modes: Audio and AirPlay. Otherwise, the OS will terminate your application after a few minutes in real conditions (without a debugger or tool).
source share