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

4

3 回答 3

6

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

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
于 2013-02-25T12:06:41.770 回答
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

    }

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

于 2013-02-25T12:11:01.327 回答
1

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

于 2013-02-25T12:07:48.367 回答