iOS 9检测静音模式

问题描述:

我一直在寻找很长一段时间,我很确定我现在无法实现我正在尝试做的事情。 我在放弃之前作为最终尝试发布在这里。 我试图实现的是检测我目前是否处于静音模式或不在我的应用程序中。 事情是,我找到了一个解决方法(播放假声音和检查完成),工作正常,但不是当我在AVAudioSessionCategoryPlayAndRecord模式。 这正是我可以录制音频和视频的屏幕,我想要实现这一点,以便知道我是否应该播放UI声音。iOS 9检测静音模式

综上所述,我尝试在AVAudioSessionCategoryPlayAndRecord模式下找到一种检测静音模式的方法。

谢谢你的时间! Nicolas

+0

对此是否有帮助? http://*.com/a/16474863/655548 – gvuksic

+0

是的,谢谢。这就是为什么我认为我试图做一些不可能的事情......但仍然在寻找一些可以使它成为可能的巧妙技巧! – nicolas

下面是一个解决方案,试图通过简单地将音频会话类别切换到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; 
    } 
}