3 回答
TA贡献1860条经验 获得超8个赞
JPM。实际上,你提供的链接会得到正确的答案(最终。;)为了完整性(因为SO应该是QUICK答案的来源!)......
// "Ambient" makes it respect the mute switch// Must call this once to init sessionif (!gAudioSessionInited){ AudioSessionInterruptionListener inInterruptionListener = NULL; OSStatus error; if ((error = AudioSessionInitialize (NULL, NULL, inInterruptionListener, NULL))) { NSLog(@"*** Error *** error in AudioSessionInitialize: %d.", error); } else { gAudioSessionInited = YES; }}SInt32 ambient = kAudioSessionCategory_AmbientSound;if (AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (ambient), &ambient)){ NSLog(@"*** Error *** could not set Session property to ambient.");}
TA贡献1827条经验 获得超4个赞
-(BOOL)silenced { #if TARGET_IPHONE_SIMULATOR // return NO in simulator. Code causes crashes for some reason. return NO; #endif CFStringRef state; UInt32 propertySize = sizeof(CFStringRef); AudioSessionInitialize(NULL, NULL, NULL, NULL); AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state); if(CFStringGetLength(state) > 0) return NO; else return YES; }
TA贡献1784条经验 获得超7个赞
如果您不在静音模式下,其他答案中的某些代码(包括接受的答案)可能不起作用,其中静音开关受到尊重。
我编写了下面的例程切换到环境,读取开关,然后返回到我的应用程序中需要的设置。
-(BOOL)muteSwitchEnabled {
#if TARGET_IPHONE_SIMULATOR
// set to NO in simulator. Code causes crashes for some reason.
return NO;
#endif
// go back 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),
&ASRoute
);
}
else
// Devices with no mike 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;
}
- 3 回答
- 0 关注
- 608 浏览
添加回答
举报