Whenever your app finishes work it should notify the user. Adding a short notification sound is one of the simplest things you can do.
First, you need to get a nice sound sample. There are some websites providing clicks and dings and dongs and swuuushes. I love www.oringz.com because the sounds are great and free (it’s always nice to tell author what you gonna do with his work). Place the mp3 file somewhere in your project so it will get in your bundle.
Now to the coding part. Add another framework called “AVFoundation” to your project. It includes the class we will use. Now you need to decide where you want to invoke the playback. I mostly take the main view controller where I import the AVFoundation headers:
#import <AVFoundation/AVFoundation.h>
An instance variable holds the sounds so we do not need to re-create it every time we want to play it:
AVAudioPlayer *newMessageAudioPlayer;
To actually play the sound, we need a little method doing the dirty work:
-(void)playNewMessagesNotification {
if (newMessageAudioPlayer == nil) {
NSURL *audioFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"notification1" ofType:@"caf"]];
newMessageAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFile error:NULL];
}
[newMessageAudioPlayer play];
}
The dirty work done here isn’t dirty at all. It checks if the audio player does exist and of not it creates it by passing a NSURL holding the mp3 filename from the bundle. After creating (or not creating) the player itself it simply starts the playback.
Finally we need to clean up. There are two things to consider. Of course, the instance variable needs to be releases when the class itself gets deallocated. And you should be aware of the memory the sound occupies when hanging around as instance variable. Lucky us, we can easily release the sound in cases of low memory since the play method re-creates it if necessary. So add this to the view controllers didReceiveMemoryWarning method:
[newMessageAudioPlayer release];
newMessageAudioPlayer = nil;