Alex Rivera | Logout

How to detect iphone is on silent mode

Asked 2009-05-07T07:20:26.150
19

I am developing an application. In that i want to detect through coding that "is iPhone on silent mode or not?". I am developing it by using cocoa with Objective-C.

If anyone knows it kindly reply.

Edit
Report

2 Answers

19

The reason Pirripli's code does not work is that the simulator does not support the test and the code does not check for errors. Corrected code would look like:

CFStringRef state = nil;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
OSStatus status = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);

if (status == kAudioSessionNoError)
{
    return (CFStringGetLength(state) == 0);   // YES = silent
}
return NO;
answered 2011-02-15T15:51:03.930
3

For completeness, building off this link from Dan Bon, I implement the following method to solve this problem in my apps. One thing to note is that the code checks for the iPhone simulator first - executing the below code will crash the simulator. Anyone know why?

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

}

Declaring this right in the view controller, you'd simply check

if ([self silenced]) {
     NSLog(@"silenced");

else {
     NSLog(@"not silenced");
}

Or, obviously, you could declare it in some kind of helper class. A more elegant solution might be a category addition on UIApplication or some such other class...

answered 2011-01-15T18:15:41.910

Your Answer