19
votes

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.

5
you need to use a different type of audio sessionbkbeachlabs

5 Answers

26
votes

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];
7
votes

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];
}
6
votes

Based on SujithPt's Answer here is the same thing in swift:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
3
votes

For Swift 4.2

import AVFoundation

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    do {
        try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
    } catch let error {
        print(error.localizedDescription)
    }

    return true
}
1
votes

For Swift 2.2, add this anywhere before you play or preparetoplay:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)