AVAudioPlayer affects system sounds

心不动则不痛 提交于 2019-12-24 09:37:20

问题


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.



来源:https://stackoverflow.com/questions/18299493/avaudioplayer-affects-system-sounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!