How do you force audio to come out of the iPhone speaker when a headset is attached?
I'm trying to add a loudspeaker feature to one of开发者_运维问答 my iPhone apps. I already created the recording functionality, but when I play the recorded audio it only plays to the phone headset.
What I need is the recorded file to be played on the loudspeaker, even if there is a headset attached. How could I reroute the audio to do this?
You need to override the default audio properties using AudioSessionSetProperty
. Look at something like this to force all audio to go to the speaker (note that this will even happen if headphones are plugged in).
OSStatus err = 0;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
err = AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,sizeof(audioRouteOverride),&audioRouteOverride);
To detect the headphones, try this (this is literally copy/paste code off of another SO post, so caveat emptor, but it works for me):
/**
* Tells us if the headset is plugged in
*/
- (BOOL) headsetIsPluggedIn
{
BOOL returnVal = NO;
UInt32 routeSize = sizeof(CFStringRef);
CFStringRef route = NULL;
OSStatus error = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &routeSize, &route);
if (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound))
{
CFRelease(route);
returnVal = YES;
}
return returnVal;
}
EDIT: There is a bit of a discussion in the comments about whether the CFRelease is appropriate or not. Any hardcore Core Foundation experts care to weigh in?
精彩评论