Sunday, April 17, 2011

Playing sound samples on the iPhone

Hi,

I've reached the point where i want to play some samples in my game/app. My instinct says use openAL ... I will have the situation where I will need to play multiple samples at once (however no more than 2 or 3) and the samples will be short (2 or 3 seconds).

My question is what is the best way of playing samples on the iPhone given that criteria?

Cheers Rich

From stackoverflow
  • This is a piece of sample code I am using:

    1st option:

    I defined this in my .h file

    SystemSoundID topClick;
    

    And in my .m file I firest load the sound (aiff file):

    NSBundle* bundle = [NSBundle mainBundle];
    NSString *topClickFile = [bundle pathForResource:@"top_click" ofType:@"aiff"];
    

    Then, when I want to play the sound, I use:

    AudioServicesPlaySystemSound(topClick);
    

    2nd option:

    You could also use the AVAudioPlayer (available since firmware 2.2 I think):

    NSString *graffitiSprayFile = [bundle pathForResource:@"sound_effect" ofType:@"aiff"];
    AVAudioPlayer* sprayAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:graffitiSprayFile] error:NULL];
    sprayAudio.delegate = self;
    [sprayAudio prepareToPlay];
    [sprayAudio setNumberOfLoops:999];
    

    The first option is very usable for relatively short sound effect.

    John Fricker : Just a point of information - AVAudioPlayer can play multiple caf, aiff, wav files but only one mp3 can play at a time (so don't use mp3 for game effects).
    Rich : Also setting the number of loops to -1 will make the sample repeat forever.
    Bill : Is a call to AudioServicesCreateSystemSoundID required?
    Rocker : Can I ask a question? how can I maximize the volum of the sound by code? thanks a lot

0 comments:

Post a Comment