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



我的代码:

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

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

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if(CFStringGetLength(state) == 0)
{
//SI
    else
    {
    //NOT SILENT
    }

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

您需要使用AVAudioSessionCategoryAmbient进行音频会话。浏览音频会话编程指南。

最新更新