This is where I’ll be making some of my personal code open source as well as sharing some of my personal snippets for the developer community. Obviously sharing clean and easy-to-digest code and tutorials takes significant time. I will try my best with my hectic schedule. Sharing is caring. ;)

AVAudioSession Speaker Fix

Below is a code snipped that quickly solved what could have been a huge problem. In the development of the Affirmation Labs iOS App, I set a session up so my affirmation audio can loop and continue in the background regardless of home-button push and device lock. After this behemoth task and trickery was completed, I realized that during my AVAudioSession with Category set to AVAudioSessionCategoryPlayAndRecord, I had a huge issue with volume decreasing when the session was enabled. Once I created the fix for directing audio forcefully to the iOS speaker to retain my max volume level, I ran into another bug that certainly stumped me. When I would plug in headphones and unplug them during the audio session, the audio would revert off of the speaker and I would hear a huge decrease in iPhone audio. Much love to Jonas on StackOverflow for figuring this out and sharing it with the community. I’ve re-posted the code as a kickoff to my “Code” category on my blog as it certainly saved me a tone of time and investigation and is quite simple and elegant.

NSError *setCategoryErr = nil;

NSError *activationErr  = nil;

//Set the general audio session category

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryErr];

//Make the default sound route for the session be to use the speaker

//Jonas' Code Begins ---------------

UInt32 doChangeDefaultRoute = 1;

AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute);

//Jonas' Code Ends ----------------

//Activate the customized audio session

[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];