user user - 1 year ago 190
Objective-C Question

How can I add sound to a button in iOS?

I would like to make a sound play when a button is pressed. Also, there is more than one sound. I am using Xcode 4.4.1 and Storyboard.

In the .h file

IBOutlet UIButton *playSound;

Answer Source

I thought it would be fun to write this type example so I wrote it. It demonstrates how to play different random sound when button is pressed:

-(IBAction)buttonPressedWithSound:(id)sender {

    int randomSoundNumber = arc4random() % 4; //random number from 0 to 3

    NSLog(@"random sound number = %i", randomSoundNumber);

    NSString *effectTitle;

    switch (randomSoundNumber) {
        case 0:
            effectTitle = @"sound1";
        case 1:
            effectTitle = @"sound2";
        case 2:
            effectTitle = @"sound3";
        case 3:
            effectTitle = @"sound4";


    SystemSoundID soundID;

    NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"caf"];
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];

    AudioServicesCreateSystemSoundID ((CFURLRef)soundUrl, &soundID);


  • Add four sounds in Your project: sound1.caf, sound2.caf, sound3.caf and sound4.caf.

  • Import AudioToolbox framework to Your project. And include in .h #import <AudioToolbox/AudioToolbox.h>.

  • Don't forget to connect Your button to buttonPressedWithSound via IBAction.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download