Reputation: 1108
I have an app that needs to use AVAudioSessionCategoryPlayback
in order to play sound while the device is locked or my app is in the background. (It's an alarm feature.) So I also need to set the "audio" key in my UIBackgroundModes list.
I have put the following code in my application:didFinishLaunchingWithOptions:
method:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
However, I don't want to interrupt any music that is already playing on the device. When my app is launched, it causes Spotify (for example) to stop playing music. I can switch to Spotify and press play, and when I switch back to my app, it continues playing.
But this is very annoying to the user - alarms are not the only thing my app does, and there are many reasons for them to launch it that don't involve setting alarms. I don't think the user would ever want my app to stop any other audio playing on the device.
Ideally I'd never interrupt already-playing audio. I could also live with stopping audio when an alarm is set (at which point I have to activate my audio session to ensure that I'm able to play it) but it seems like there is no way for me to avoid the audio stop at app launch.
Is there some way to start my app with the audio session disabled, or to start it with this option already applied?
Upvotes: 4
Views: 2517
Reputation: 1108
It turns out that I was calling .prepareForPlayback()
on an AVAudioPlayer in an init()
method which was getting called long before my didFinishLaunchingWithOptions:
fired.
Upvotes: 2