Wednesday, April 18, 2012

App sounds cause iPod music, Pandora or Pod cast sound to stop

we have different sounds for actions and buttons within our app. We've heard a number of complaints where users background music stops as soon as one of our sounds is played. We're not quite sure why this is happening. Here is the code we're using to toggle our sounds.



- (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];
}
}


Update: We've actually ended up changing the above to the following per a few users suggestions. This allows iPod music or pod casts to continue and our sounds to play without stopping this background sound. This is possible by setting our sounds as "ambient" sound. This requires that you add the "AudioToolBox" framework and import this framework into your class using the following,



#import <AudioToolbox/AudioToolbox.h>


Here is the code we're using now,



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

}




No comments:

Post a Comment