The nice thing about AVAudioPlayer is that it's a piece of cake to use. The downside is that it isn't instantaneous, so you’ll get a slight pause before the sound plays. So, I’ve found that it’s great for playing alerts and things like that, but not for anything that requires immediate playback, like games or a virtual piano.
Loading a sound and playing it is simple. To load a piece of audio, use something like this:
AVAudioPlayer *myExampleSound;
NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"myaudiofile" ofType:@"caf"];
myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];
myExampleSound.delegate = self;
NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"myaudiofile" ofType:@"caf"];
myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];
myExampleSound.delegate = self;
The second and third lines are fairly common for loading files – point to the file, then assign said file to your variable. The third line, which I believe is optional for simple stuff, basically tells the view (I think) to pay attention to the sound so that you can monitor what it’s doing.
Anyway, once the file is loaded, playing (and stopping) it is simple. Those commands look like:
[myExampleSound play];
[myExampleSound stop];
Before you play the sound, you can use:
[myExampleSound prepareToPlay];
to get it ready. AVAudioPlayer will do this for you automatically when you call the play method, but you then get a tiny bit more lag. If it’s a short sample, you’ll probably be fine without it.
Aside from playing and stopping the sound, you can tweak it in a few ways. Here are two examples:
myExampleSound.volume = 0.5;
myExampleSound.numberOfLoops = 2;
Obviously, the first one sets the volume (from 0 to 1.0) and the second can be used to repeat the sound multiple times in a row.
There are a couple more things you can do with AVAudioPlayer, though I haven’t played around with more myself. For instance, it sounds like you can monitor whether or not a sound is currently playing, which can certainly be helpful.