3
votes

I'm programming an application that plays background music, and to do so I am using AVAudioSession like so:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"song" ofType:@"mp3"]];
player = [[AVAudioPlayer alloc] initWithData:data error:NULL];
player.delegate = self;
[player setVolume:1.0];
...
[player prepareToPlay];
[player play];

Then, later, the user has the option to disable music. If they choose to do so, the following code is run:

[[AVAudioSession sharedInstance] setActive:NO error:nil];
[player stop];

Which successfully stops the music from playing. However, if music from the Music app (or another, like Spotify) is started, and then the app is switched to, the users music will fade out and pause. My app's music will not play, since it is still disabled, so the user is then left in silence.

How can I keep my app from pausing the user's music?

2
Why don't you make a logical control? If the user chooses to disable music, you just stop you AVAudioPlayer. Is there a need do call [[AVAudioSession sharedInstance] setActive:NO error:nil]? - Marcelo Fabri
That was added in an attempt to solve the problem. Initially, I was just stopping the player, but that still caused this issue. - Jumhyn
Plus, if the user deactivates the music, doesn't it make sense to set the audio session to inactive? - Jumhyn
Try to remove setActive: and call [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; - Marcelo Fabri
That worked! Submit as an answer and I'll accept. - Jumhyn

2 Answers

10
votes

You have to do the following when the user chooses to remove audio:

[player stop];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
3
votes

You need to set your audio session category

NSError *categoryError = nil;
[audioSession setCategory: AVAudioSessionCategoryAmbient error: &categoryError];

If you set it to AVAudioSessionCategorySoloAmbient (which is default), it will kill the background music and let your app take over, even if you're not playing music. It may be best to set it to SoloAmbient when you do intend to play music, and set it to Ambient when the user disables the music.