Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 484
user Avatar asked Aug 09 '12 16:08

user


People also ask

How do I add Sounds to Apple?

Go to Settings > Accessibility > Audio/Visual > Background Sounds, then turn on Background Sounds. Set any of the following: Sound: Choose a sound; the audio file downloads to your iPhone.

How do you add sound effects to iMovie?

Tap the Add Media button, tap Audio, then tap Sound Effects to browse the built-in sound effects. Tap a sound effect to preview it. To add a sound effect, tap the Add Audio button next to the sound effect.


2 Answers

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";
            break;
        case 1:
            effectTitle = @"sound2";
            break;
        case 2:
            effectTitle = @"sound3";
            break;
        case 3:
            effectTitle = @"sound4";
            break;

        default:
            break;
    }

    SystemSoundID soundID;

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

    AudioServicesCreateSystemSoundID ((CFURLRef)soundUrl, &soundID);
    AudioServicesPlaySystemSound(soundID);  
}

Explanation:

  • 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.

like image 125
Justin Boo Avatar answered Oct 11 '22 01:10

Justin Boo


I have found this way, and it works for me

SystemSoundID soundID;
NSString *soundPath = [[NSBundle mainBundle] pathForResource:ClickSoundFile ofType:FileTypemp3];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID);
AudioServicesPlaySystemSound(soundID);

*Note

ClickSoundFile : Sound file name FileTypemp3 : file type mp3

like image 21
Rahul K Rajan Avatar answered Oct 11 '22 00:10

Rahul K Rajan