我想在按下按钮时播放声音。此外,还有不止一种声音。我正在使用 Xcode 4.4.1 和 Storyboard。
在.h文件中
{
IBOutlet UIButton *playSound;
}
最佳答案
我觉得写这个类型的例子会很有趣,所以我写了它。它演示了如何在按下按钮时播放不同的随机声音:
-(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.caf、sound2.caf、sound3.caf 和 sound4 .caf.
将 AudioToolbox 框架导入您的项目。并包含在 .h
#import <AudioToolbox/AudioToolbox.h>
中.不要忘记通过
IBAction
将您的按钮连接到 buttonPressedWithSound .
关于objective-c - 如何为 iOS 中的按钮添加声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11888059/