我怎样才能将声音添加到iOS中的button?

我想在按下button时播放声音。 另外,还有不止一个声音。 我正在使用Xcode 4.4.1和Storyboard。

在.h文件中

{ IBOutlet UIButton *playSound; } 

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

 -(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将你的button连接到buttonPressedWithSound

我已经find了这种方式,它对我有用

 SystemSoundID soundID; NSString *soundPath = [[NSBundle mainBundle] pathForResource:ClickSoundFile ofType:FileTypemp3]; NSURL *soundUrl = [NSURL fileURLWithPath:soundPath]; AudioServicesCreateSystemSoundID ((__bridge CFURLRef)soundUrl, &soundID); AudioServicesPlaySystemSound(soundID); 

*注意

ClickSoundFile:声音文件名称FileTypemp3:文件typesmp3