Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS AVAudioPlayer makes other app's background music stopped

Tags:

ios

iphone

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.

like image 730
user1519520 Avatar asked Jul 12 '12 02:07

user1519520


People also ask

Does Apple music have background play?

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.


2 Answers

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];
like image 68
Sujith Thankachan Avatar answered Oct 13 '22 18:10

Sujith Thankachan


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];
}
like image 30
charles Avatar answered Oct 13 '22 20:10

charles