2013-02-25 136 views
0

我的代码:如何停止播放声音,如果静音模式开启时

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!"); 
    } 
} 

当我切换iPhone到静音模式的声音仍然起着。我怎么解决这个问题?

回答

6

我还没有尝试过,但你可以在播放文件之前设置音频类别:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil]; 
2
CFStringRef state; 

UInt32 propertySize = sizeof(CFStringRef); 

AudioSessionInitialize(NULL, NULL, NULL, NULL); 
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state); 
if(CFStringGetLength(state) == 0) 
{ 
//SI 

    else 
    { 
    //NOT SILENT 

    } 

可以检测手机的状态,并停止播放.. :)

+1

+1,那是很好的阿努拉格,尼斯一块代码 – mAc 2013-02-25 12:23:12

+0

欢迎的Mac :) ... :-) – 2015-01-05 06:39:33