2013-02-25 31 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