2016-03-15 95 views
2

我一直在尋找很長一段時間,我很確定我現在無法實現我正在嘗試做的事情。 我在放棄之前作爲最終嘗試發佈在這裏。 我試圖實現的是檢測我目前是否處於靜音模式或不在我的應用程序中。 事情是,我找到了一個解決方法(播放假聲音和檢查完成),工作正常,但不是當我在AVAudioSessionCategoryPlayAndRecord模式。 這正是我可以錄製音頻和視頻的屏幕,我想要實現這一點,以便知道我是否應該播放UI聲音。iOS 9檢測靜音模式

綜上所述,我嘗試在AVAudioSessionCategoryPlayAndRecord模式下找到一種檢測靜音模式的方法。

謝謝你的時間! Nicolas

+0

對此是否有幫助? http://stackoverflow.com/a/16474863/655548 – gvuksic

+0

是的,謝謝。這就是爲什麼我認爲我試圖做一些不可能的事情......但仍然在尋找一些可以使它成爲可能的巧妙技巧! – nicolas

回答

1

下面是一個解決方案,試圖通過簡單地將音頻會話類別切換到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; 
    } 
}