如何在iOS中为按钮添加声音?

use*_*ser 5 objective-c nssound ios

我想在按下按钮时发出声音.此外,还有不止一种声音.我正在使用Xcode 4.4.1和Storyboard.

在.h文件中

{
    IBOutlet UIButton *playSound;
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*Boo 20

我认为写这个类型的例子会很有趣,所以我写了它.它演示了按下按钮时如何播放不同的随机声音:

-(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);  
}
Run Code Online (Sandbox Code Playgroud)

说明:

  • 在您的项目中添加四个声音:sound1.caf,sound2.caf,sound3.caf和sound4.caf.

  • 将AudioToolbox框架导入您的项目.并包括在.h #import <AudioToolbox/AudioToolbox.h>.

  • 不要忘记将您的按钮连接到buttonPressedWithSound via IBAction.