Changing iPhone audio session categories

For the past few hours I’ve been slamming my head against the wall trying to get these features working together: background playback of iPod audio, OpenAL playback of in-game events, and microphone recording. Microphone recording is not compatible with iPod audio and that is OK. When I enable the mic midway through program execution all I wanted to do was switch the session category and let the OS kill the music but it wasn’t working. I finally came up with a workaround and am writing this up for anyone else who runs into this issue.

Problem #1: don’t initialize OpenAL before initializing an audio session explicitly. If you do, iPod audio will be killed as OpenAL comes up. I couldn’t find any documentation on how this affects the session category.

To let the iPod continue to play you need to initialize an audio session and set the category to kAudioSessionCategory_UserInterfaceSoundEffects or kAudioSessionCategory_AmbientSound (info here). Make sure you do this first.

Problem #2: the OS will not let you change session categories if you first set your audio session – as above – and then start OpenAL. Why? I have no idea, the error code the API function returns is not a documented error.

I had to completely tear down OpenAL first and then call AudioSessionSetActive(false); to shutdown my initial audio session. Then I was able to change the category, restart the session, and finally restart OpenAL. Yes, this also means that I have to free all of my application’s sounds and reload them. This causes additional time the user has to wait for the sounds to reload. In the end it works but is not pretty.

2 Responses to “Changing iPhone audio session categories”

  1. Lane Roathe says:

    To save your users the time on reloading of your sound data, be sure you are sending the sound data to OpenAL using Apple’s iPhone extension alBufferDataStaticProcPtr which lets OpenAL use the data in-place (no mem copies, which are VERY slow on device). oalTouch has an example use of this extension.

  2. Mark Cooke says:

    Thanks for the tip!

Leave a Reply