How to add sound to a button in iOS?

I want to make audio playback when I press a button. In addition, there is more than one sound. I am using Xcode 4.4.1 and Storyboard.

In the .h file

{
    IBOutlet UIButton *playSound;
}
+5
source share
2 answers

I thought it would be interesting to write this type example so that I write it. It demonstrates how to play various random sounds at the touch of a button:

-(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 to your project: sound1.caf, sound2.caf, sound3.caf and sound4.caf.

  • Import the AudioToolbox infrastructure into your project. And include in .h #import <AudioToolbox/AudioToolbox.h>.

  • Remember to connect your button to buttonPressedWithSound through IBAction.

+20
source

I found this method 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:  FileTypemp3: mp3

+1

All Articles