我想在按下按钮时播放声音。此外,有多个声音。我正在使用Xcode 4.4.1和故事板。
在.h文件中:
在.h文件中:
{
IBOutlet UIButton *playSound;
}
{
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。
NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"mp3"];
- Justin BooSystemSoundID 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