我尝试使用以下方法来检测Ring/Silent开关是否处于活动状态:
但在我的iPhone 4上,“state”值始终为“Speaker”(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日更新:如果您想检测静音开关,则SoundSwitch库是正确的选择,虽然它有点像黑客,而且我在我的iPhone 5S上使用多任务处理它时遇到了崩溃,但它甚至可以在iOS 7中工作。
deviceIsSilenced
,感谢你的提问,Jane! :) - taber