如果打开静音模式,如何停止播放声音

时间:2013-02-25 11:50:43

标签: iphone ios objective-c avaudioplayer

我的代码:

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切换到静音模式时,声音仍在播放。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

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

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];

答案 1 :(得分: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

    }

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

答案 2 :(得分:1)

您需要使用AVAudioSessionCategoryAmbient进行音频会话。通过audio session programming guide

相关问题