1

我们的应用程序中的动作和按钮有不同的声音。我们听到了许多抱怨,即用户的背景音乐在播放我们的声音后立即停止。我们不太确定为什么会这样。这是我们用来切换声音的代码。

- (void)playSound:(NSString *)sound {

if ( playSoundPath == nil ) {
    playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
    playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
    playSound.delegate = self;
}else{
    playSoundPath = nil;
    [playSound release];
    playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
    playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
    playSound.delegate = self;
}
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"sounds_key"];
if ( enabled ){
    [playSound stop];
    [playSound play];
}
}

更新:实际上,根据一些用户的建议,我们最终将上述内容更改为以下内容。这允许 iPod 音乐或播客继续播放,并且我们的声音可以在不停止背景声音的情况下播放。这可以通过将我们的声音设置为“环境”声音来实现。这需要您添加“AudioToolBox”框架并使用以下内容将此框架导入您的类中,

#import <AudioToolbox/AudioToolbox.h>

这是我们现在使用的代码,

BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"sounds_key"];
if ( enabled ){

    AudioSessionInitialize(NULL, NULL, NULL, self);
    UInt32 category = kAudioSessionCategory_AmbientSound;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);  
    AudioSessionSetActive(YES);

    NSString *path = [NSString stringWithFormat:@"%@/%@.wav",[[NSBundle mainBundle] resourcePath], sound];

    SystemSoundID soundID;

    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];

    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);

    AudioServicesPlaySystemSound(soundID);

}
4

0 回答 0