tags:

views:

4715

answers:

5

I've gotten to play a single sound in the iPhone app I've started, but I now desire to play multiple sounds based on a button. To create a separate set of .m and .h files for each audio sounds, and then including them all, doesn't seem the most efficient way to tackle this in terms of coding...then again, I'm just starting out with Cocoa and only just completed my first app ever.

Any help is appreciated. The key here is multiple sounds, each triggered by its own button or image. Thanks.

+7  A: 

Please don't make another fart app. I'm begging you.

JW
That is the best iPhone application......
Michael Kniskern
well...whatever customers desire. fart apps, for sure.
HelloMoon
Huahauahauahuahaahahaaahuaa. Very funny.
R31n4ld0_
+2  A: 

I don't have any direct experience with iPhone development, but in theory could you create a single large sound file with all your sounds in it? Each sound could be separated by just enough silence to be individually accessed by a time index. Of course, the downside is that you'd have to load the entire file into memory, unless you could figure out a way to load chunks in a random-access fashion...

Dave Swersky
+3  A: 

If you have access to the iPhone developer network, then there are a bunch of code samples that show you how to play audio.

All you need to do is make one class that has a function called

-(void)Play:(NSString*)sSoundFile {
    // play sound file here
}
Michael Pryor
+5  A: 

If the files are MP3 or AAC format, then you can only play one at a time. This is a limitation of core audio on the iPhone.

In terms of playing multiple sounds at once, that's easy, just create a new player instance for every one that you want to play (and remember to release them when you're done)

NSString *path = [[NSBundle mainBundle] pathForResource:@"dream" ofType:@"m4a"];  
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  
theAudio.delegate = self;  
[theAudio play];

To convert an MP3 into something like IMA4 (which you can play more than one at once) you would run the following (in terminal, in leopard):

/usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf

The above code is firmware 2.2 only, but you can do the same with the AudioQueue files if you want to support older firmwares (it's just a lot more complex, so I haven't listed the code here).

rustyshelf
+1  A: 

@rustyshelf - does this work in the simulator? I'm using that code, and using #import but neither audioPlayerDidFinishPlaying nor audioPlayerDecodeErrorDidOccur ever get called. Very annoying to try to debug.

John
Aha - I figured it out, sort of. Make sure you disable any bluetooth audio devices on the simulator..http://www.iphonedevsdk.com/forum/iphone-sdk-development/2362-bluetooth-error-simulator.html
John