Quantcast
Channel: Inchoo » Ivan Kalaica
Viewing all articles
Browse latest Browse all 24

How to add custom sound effects to iPhone app?

$
0
0

Here is simple code snippet (class) that enables you to add custom sound effects to iPhone application. As you can see procedure is fairly simple.

I always like to prepare app for future changing, for example, if one day I change my mind and want to change existing clicking sound with new one I don’t have to change it everywhere I have create it, I just change value of effect string instance that is implemented in custom made Sound class in static method + (void) soundEffect:(int)soundNumber.

You can see here that I used static method so I don’t have to create instance of that class just to play a sound. When you want to call sound effect from another class just add this line of code [SoundAlert soundEffect:1]; to play for example an click sound effect.  I recommend you to put this call in viewWillDisappear: method so that sound triggers every time when current view exits.

Now finnaly if I want this class to work without errors I must add sound files. Isn’t that logical or what? I am using .aif  audio file so I must be sure to set type string instance value to @”aif” and also set the name of audio file with same name as value of effect string instance. Here is Sound class.

Sound.h

#import <foundation /Foundation.h>
#import <audiotoolbox /AudioToolbox.h>
@interface Sound : NSObject {
}
+ (void) soundEffect:(int)soundNumber;
@end

Sound.m

#import "Sound.h"
@implementation Sound
+ (void) soundEffect:(int)soundNumber {
NSString *effect;
NSString *type;
if (soundNumber == 0) {
effect = @"intro";
type = @"wav";
}
else if (soundNumber == 1) {
effect = @"click";
type = @"aif";
}
else if (soundNumber == 2) {
effect = @"error";
type = @"aif";
}
NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:@"sound"];
if ([value compare:@"ON"] == NSOrderedSame) {
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle] pathForResource:effect ofType:type];
NSURL *url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID ((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound(soundID);
}
}
- (void)dealloc {
[super dealloc];
}
@end

I have also added switch somewhere in my costume made settings menu that enables user to turn OFF or ON all custom used sounds in app. Here we are checking in which state is switch and if it is on ON position sound will play. You can see how to use NSUserDefaults to save state of switch in my previously post. That’s all!


Viewing all articles
Browse latest Browse all 24

Trending Articles