我想在按下按钮时发出声音。此外,还有不止一种声音。我正在使用Xcode 4.4.1和Storyboard。
在.h文件中
{
IBOutlet UIButton *playSound;
}
答案 0 :(得分: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);
}
说明:
在您的项目中添加四个声音: sound1.caf , sound2.caf , sound3.caf 和 sound4的.caf
将AudioToolbox框架导入您的项目。并包含在.h #import <AudioToolbox/AudioToolbox.h>
。
不要忘记通过IBAction
将您的按钮连接到 buttonPressedWithSound 。
答案 1 :(得分:1)
我找到了这种方式,它对我有用
SystemSoundID soundID;
NSString *soundPath = [[NSBundle mainBundle] pathForResource:ClickSoundFile ofType:FileTypemp3];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID);
AudioServicesPlaySystemSound(soundID);
*注
ClickSoundFile:声音文件名 FileTypemp3:文件类型mp3