我尝试使用这些方法来检测响铃/静音开关是否处于活动状态:
但在我的 iPhone 4 上,“状态”值始终为“扬声器”(CFStringGetLength(state) 返回的长度值始终为 7)。有没有人成功使用过这个方法?如果是这样,在什么样的设备和 SDK 版本上?
我这样称呼它:
- (BOOL)deviceIsSilenced {
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus audioStatus = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if (audioStatus == kAudioSessionNoError) {
NSLog(@"audio route: %@", state) // "Speaker" regardless of silent switch setting, but "Headphone" when my headphones are plugged in
return (CFStringGetLength(state) <= 0);
}
return NO;
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
audioSession.delegate = self;
[audioSession setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioSession setActive:YES error:nil];
NSLog(@"muted? %i", [self deviceIsSilenced]);
...
}
我在想,当手机上的物理开关被切换时,可能会触发其他一些(更准确的)kAudioSessionProperty 事件。有人有想法么?
顺便说一句,我将 AVAudioSessionCategoryAmbient 类别与我的 [AVAudioSession sharedInstance] 一起使用。
更新:我也尝试过使用不同的音频类别和一些其他音频会话属性,在静音/取消静音开关时似乎没有触发。:(
2014 年 1 月 1 日更新:这有点骇人听闻,我在 iPhone 5S 上进行多任务处理时遇到了崩溃,但如果您想检测静音开关。它甚至适用于 iOS 7。