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

6
我想在按下按钮时播放声音。此外,有多个声音。我正在使用Xcode 4.4.1和故事板。
在.h文件中:
{
    IBOutlet UIButton *playSound;
}

1
请展示您目前的工作成果;不太可能有人会为您编写一个项目。 - Dustin
我正在修改您的问题标题,将其中的Xcode删除。Xcode只是开发环境而已。您真正关心的是您想在iOS下完成这个操作。 - Michael Dautermann
实际上,Cocoa-Touch 才是重要的,因为它是他在 iOS 中使用的 API。 :) - Almo
{ 在 .h 文件中: IBOutlet UIButton *playSound; } - user
2个回答

22

我觉得写这个演示例子应该很有趣,所以就写了。它演示了如何在按下按钮时播放不同的随机声音:

-(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);  
}

说明:

  • 在您的项目中添加四个声音文件:sound1.cafsound2.cafsound3.cafsound4.caf

  • 导入AudioToolbox框架到您的项目中,并在.h文件中包含#import <AudioToolbox/AudioToolbox.h>

  • 别忘了通过IBAction将您的按钮连接到buttonPressedWithSound


@KyleGreenlaw 您之所以收到此消息,是因为您没有将AudioToolbox框架包含在项目中(请查看底部的说明)。 - Justin Boo
我可以使用 mp3 文件而不是 caf 文件吗? - user
当然可以,只需要像这样将类型更改为mp3:NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"mp3"]; - Justin Boo
@JustinBoo 谢谢。我一直在寻找一个合适的按钮按下声音效果,但似乎找不到合适的。这就是为什么我要求源代码的原因。我不认为我的用户会喜欢从soundbible中听到汽车标签声音当他们按下按钮。 - Zorayr
@JustinBoo 在这种情况下,"mp3" 对我不起作用,我必须将声音转换为 .caf 格式。 - Boris Y.
显示剩余2条评论

1
我找到了这种方法,对我很有效。
SystemSoundID soundID;
NSString *soundPath = [[NSBundle mainBundle] pathForResource:ClickSoundFile ofType:FileTypemp3];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID);
AudioServicesPlaySystemSound(soundID);

*注意

ClickSoundFile:声音文件名称 FileType mp3:文件类型为mp3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接