Reputation: 2552
My code:
NSString *soundName = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL *soundURL = [NSURL fileURLWithPath:soundName];
NSError *error = [[NSError alloc] init];
self.backgroundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
if (self.backgroundPlayer == nil) {
NSLog(@"error = %@",[error description]);
} else {
[self.backgroundPlayer setDelegate:self];
[self.backgroundPlayer setNumberOfLoops:HUGE_VAL];
[self.backgroundPlayer setVolume:0.5f];
[self.backgroundPlayer prepareToPlay];
if ([self.backgroundPlayer prepareToPlay]) {
if ([self.backgroundPlayer play]) {
NSLog(@"playing");
}
} else {
NSLog(@"error!");
}
}
When I switch iPhone to silent mode sound still plays. How can I solve this problem?
Upvotes: 0
Views: 1496
Reputation: 119
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if(CFStringGetLength(state) == 0)
{
//SI
else
{
//NOT SILENT
}
you can detect the state of phone and stop your player .. :)
Upvotes: 2
Reputation: 1048
You need to user AVAudioSessionCategoryAmbient for audio session. go though audio session programming guide.
Upvotes: 1
Reputation: 4140
I haven't tried this, but you can set the audio category before playing the file:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
Upvotes: 6