应用程序声音会导致iPod音乐,Pandora或Pod投射声音停止

时间:2012-04-17 19:28:17

标签: iphone objective-c xcode audio avaudioplayer

我们的应用中的动作和按钮有不同的声音。我们听过一些投诉,一旦我们的一个声音播放,用户背景音乐就会停止。我们不太确定为什么会这样。这是我们用来切换声音的代码。

- (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);

}

0 个答案:

没有答案