下面是一個解決方案,試圖通過簡單地將音頻會話類別切換到SoloAmbient(一種尊重靜音開關的類別) - 讀取開關 - 然後切換回來來讀取開關。這可能是你最好的方法。
如果交換音頻會話類別會干擾您的應用程序,我會建議在播放音頻之前進行檢查並使用您檢測到的值,然後對無聲開關進行響應。這是一個解決方法,但它應該給你一些信息。
切換到環境類別,確定靜音開關是否打開,然後將會話切換回我需要的音頻設置。在確定開關是否打開後,您需要計算出需要的音頻會話類別並切換到該類別。
-(BOOL)muteSwitchEnabled {
#if TARGET_IPHONE_SIMULATOR
// set to NO in simulator. Code causes crashes for some reason.
return NO;
#endif
// switch to Ambient to detect the switch
AVAudioSession* sharedSession = [AVAudioSession sharedInstance];
[sharedSession setCategory:AVAudioSessionCategoryAmbient error:nil];
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
BOOL muteSwitch = (CFStringGetLength(state) <= 0);
NSLog(@"Mute switch: %d",muteSwitch);
// code below here is just restoring my own audio state, YMMV
_hasMicrophone = [sharedSession inputIsAvailable];
NSError* setCategoryError = nil;
if (_hasMicrophone) {
[sharedSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &setCategoryError];
// By default PlayAndRecord plays out over the internal speaker. We want the external speakers, thanks.
UInt32 ASRoute = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (ASRoute),m&ASRoute);
} else {
// Devices with no mic don't support PlayAndRecord - we don't get playback, so use just playback as we don't have a microphone anyway
[sharedSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError) {
NSLog(@"Error setting audio category! %@", setCategoryError);
}
return muteSwitch;
}
}
對此是否有幫助? http://stackoverflow.com/a/16474863/655548 – gvuksic
是的,謝謝。這就是爲什麼我認爲我試圖做一些不可能的事情......但仍然在尋找一些可以使它成爲可能的巧妙技巧! – nicolas