Today I will explain how we can play a sound when a button is pressed, in fact, what I will explain can be used in many other situations and not only for buttons, because what I will do is to create a SystemSoundID which is used, among another things, to play short (30 seconds or less) sounds. But as an example, I will use a button.
To be able to reproduce sounds we will need to add the AudioToolbox Framework to our project.
Imagine we have a UIViewController and the view it is controlling, add a UIButton to the view using Interface Builder or do it programmatically, as you like most. If you haven’t added yet the Framework to the project, do it now, once you have done it we have to import it to our view controller.
In the header file (.h) of our controller add a variable of type SystemSoundID and a method which will be called when the button is pressed.
#import <UIKit/UIKit.h> #import <AudioToolbox/AudioToolbox.h> @interface testKeyboardViewController : UIViewController <UITextFieldDelegate> { SystemSoundID buttonSoundID; } - (IBAction)buttonPressed; @end
Now we need a sound file, with the sound we want, for example call it ButtonSound.caf, now, and in the viewDidLoad of our controller add the following lines to create the reference to our sound.
- (void)viewDidLoad { [super viewDidLoad]; NSString *path = [[NSBundle mainBundle] pathForResource:@"ButtonSound" ofType:@"caf"]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &buttonSoundID); }
As you can see in the code, we need the path for our file, if you have add the file to your group Resources in Xcode, the code above should work for you. Take a look at NSBundle if that doesn’t work to look for another method that allows you to find the path to the file.
With this we have the reference to the sound, now we only need to play it when we need, in this case, we want to play it when the button is pressed. Add to the method that is called when the button is pressed, the following lines
- (IBAction)buttonPressed { AudioServicesPlaySystemSound(buttonSoundID); }
Now you should be hearing the sound when you press the button.
When you don’t need anymore the sound, you can use the following function to remove the reference, for example in the viewDidUnload of our controller.
- (void)viewDidUnload { AudioServicesDisposeSystemSoundID(buttonSoundID); }
I hope that this post is useful and now you are able to add all kind of short sounds to your application to give it a bit more of life.