打开扬声器:
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
关闭扬声器:
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
注意:
1:iPad不需要打开关闭扬声器:因为iPad只有扬声器
2:在打开和关闭养生起的时候,需要对耳机做处理,如果当前处于耳机插入的时候,打开扬声器是没有作用的。所以需要监听当前音频轨道变化。
//添加耳机拔掉侦听事件
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioRouteChangeCallback, (__bridge void *)(self));
//耳机拔掉侦听事件回调 [AudioManager 为当前类,即为self]
void audioRouteChangeCallback(void*inClientData,AudioSessionPropertyIDinID, UInt32inDataSize,constvoid*inData)
{
CFDictionaryRefrouteChangeDictionary = inData;
CFNumberRefrouteChangeReasonRef =CFDictionaryGetValue(routeChangeDictionary,CFSTR(kAudioSession_AudioRouteChangeKey_Reason));
SInt32routeChangeReason;
CFNumberGetValue(routeChangeReasonRef,kCFNumberSInt32Type, &routeChangeReason);
AudioManager*_self = (__bridgeAudioManager*)inClientData;
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) { //拔掉耳机
[_self setSpeakerOn];
}else if (routeChangeReason ==kAudioSessionRouteChangeReason_NewDeviceAvailable) { //插入耳机
}
}
//检测当前是否有耳机:
- (BOOL)hasHeadset
{
CFStringRef route;
UInt32propertySize =sizeof(CFStringRef);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);
if((route ==NULL) || (CFStringGetLength(route) ==0))
{
// Silent Mode
}
else
{
NSString* routeStr = (__bridge_transferNSString*)route;
NSRangeheadphoneRange = [routeStrrangeOfString:@"Headphone"];
NSRangeheadsetRange = [routeStrrangeOfString:@"Headset"];
if(headphoneRange.location!=NSNotFound)
{
returnYES;
}elseif(headsetRange.location!=NSNotFound)
{
returnYES;
}
}
return NO;
}