打開揚聲器:
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
關(guān)閉揚聲器:
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
注意:
1:iPad不需要打開關(guān)閉揚聲器:因為iPad只有揚聲器
2:在打開和關(guān)閉養(yǎng)生起的時候,需要對耳機做處理砾肺,如果當(dāng)前處于耳機插入的時候淋纲,打開揚聲器是沒有作用的匈挖。所以需要監(jiān)聽當(dāng)前音頻軌道變化稠氮。
//添加耳機拔掉偵聽事件
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioRouteChangeCallback, (__bridge void *)(self));
//耳機拔掉偵聽事件回調(diào) [AudioManager 為當(dāng)前類,即為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) { //插入耳機
}
}
//檢測當(dāng)前是否有耳機:
- (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;
}