Setting up iPhone to start playback through speakers, but allow headphone override
I know this question has been somewhat dealt with before, but I feel like we could nail this down a bit better.
Here is my present code. The iPhone automatically plays out the speakers (not the earpiece), but when I plug the earphones in nothing happens. I would like it so that it playback is through the speakers, but will route through the headphones if they are plugged in. How can we change this code to properly do this?
// ORIGINAL CODE
UInt32 category = kAudioSessionCategory_PlayAndRecord;
error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
if (error) printf("couldn't set audio category!");
// I put this chunk in of code myself. To change the audio to go the speakers (not the earpiece).
// I don't think this is the best way to do this.
UInt32 audioRouteOverride = kAudioSessionOverrideAu开发者_开发百科dioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
Thanks!
I did it this way:
OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (error) printf("ERROR INITIALIZING AUDIO SESSION! %d\n", error);
else
{
UInt32 category = kAudioSessionCategory_PlayAndRecord;
// UInt32 category = kAudioSessionCategory_MediaPlayback;
error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
if (error) printf("couldn't set audio category!");
// It is bugs when I unplug the headphones!
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute);
error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, propListener, self);
if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
UInt32 inputAvailable = 0;
UInt32 size = sizeof(inputAvailable);
// we do not want to allow recording if input is not available
error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable);
if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", error);
btn_record.enabled = (inputAvailable) ? YES : NO;
// we also need to listen to see if input availability changes
error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, propListener, self);
if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
error = AudioSessionSetActive(true);
if (error) printf("AudioSessionSetActive (true) failed");
精彩评论