AVAudioPlayer affects system sounds

2019-08-11 07:24发布

问题:

I use this code to play a short sound effect. This happens when user clicks the return button of the keyboard, which makes the keyboard click sound effect louder than usual. Is it possible to play the effect at certain volume without affecting system sounds?

- (void)playCorrectAnswerSound {
NSString *path = [[NSBundle mainBundle] pathForResource:@"correct" ofType:@"mp3"];
NSURL *urlPath = [NSURL fileURLWithPath:path];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:nil];
self.player.volume = 0.04;
[self.player prepareToPlay];
[self.player play];

}

回答1:

Set your application's audio-session category to AVAudioSessionCategoryAmbient by adding the following code to your app delegate's applicationDidFinishLaunchingWithOptions: method:

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
    [[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
    [[AVAudioSession sharedInstance] setDelegate:self];

From apple's doc:

This category allows audio from the iPod, Safari, and other built-in applications to play while your application is playing audio.