I want to play sound while my app is in the background and respect the mute-ring-switch.
I managed to play sound while my app is not in the foreground. I use basically the following code to play my sound:
sound = [[AVAu开发者_Python百科dioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
sound.numberOfLoops = -1;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
/* ... */
[sound playAtTime:0];
AVAudioSessionCategoryPlayback causes my application to ignore the silent/ring-switch and play sound in background.
Since I want to have the last behavior without the first, I searched for a solution to query the state of the silent/rind-switch. I tried different approaches but this seemed to work for most of the users:
-(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;
}
I found it here: How to programmatically sense the iPhone mute switch?
This code isn't working for me. Despite the phone is muted "state" is not empty.
Does anyone have an idea, why this isn't working for me? I am developing and testing for iOS 4.3.
Thx.
Edit I used CFShow to show the content of the kAudioSessionProperty_AudioRoute and it is "Speaker" everytime, nontheless I changed the state of the mute/ring switch.
精彩评论