Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioSession blocking system audio

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?

like image 835
Jumhyn Avatar asked Sep 17 '26 09:09

Jumhyn


1 Answers

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

[player stop];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
like image 95
Marcelo Fabri Avatar answered Sep 19 '26 01:09

Marcelo Fabri