I have an exercise app which needs to play sound. I use AVAudioPlayer to play the sound. But when the audio starts to play, the background music from another app (radio streaming app) is shutdown.
How can I make it not interrupt the background music? Because I'd like the user to hear music while doing exercise.
Thank you.
Under the Capabilities tab, set the Background Modes switch to ON and select the “Audio, AirPlay, and Picture in Picture” option under the list of available modes. With this mode enabled and your audio session configured, your app is ready to play background audio.
You can use the following code where you use AVAudioPlayer:
// Set AudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
If you wish to set a delegate, you can add this line of code:
[[AVAudioSession sharedInstance] setDelegate:self];
In my case, I wanted the background audio to be played at a lower volume, as the sound played by my app is more like an alert. I use this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// prevents our app from stopping other audio,
// e.g. music, podcats, etc. that may be playing when launched
// our audio will be played at a higher volume
// and the background audio will "duck" until done
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryMultiRoute
withOptions:AVAudioSessionCategoryOptionDuckOthers
error:nil];
}
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