iOS 9检测静默模式

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

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

感谢您的时间! 萨科

下面是一个解决scheme,试图通过简单地将audio会话类别切换到SoloAmbient(一种尊重静音开关的类别) – 读取开关 – 然后切换回来来读取开关。 这可能是你最好的方法。

如果交换audio会话类别会干扰您的应用程序,我会build议在播放audio之前进行检查,并使用您检测到的值,然后对无声开关进行响应。 这是一个工作,但它应该给你一些信息。

切换到环境类别,确定无声开关是否打开,然后将会话切换回我需要的audio设置。 在确定开关是否打开之后,您将需要计算出所需的audio会话类别并进行交换。

-(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; } }