I thought it would be interesting to write this type example so that I write it. It demonstrates how to play various random sounds at the touch of a button:
-(IBAction)buttonPressedWithSound:(id)sender {
int randomSoundNumber = arc4random() % 4;
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);
}
Explanation:
Add four sounds to your project: sound1.caf, sound2.caf, sound3.caf and sound4.caf.
Import the AudioToolbox infrastructure into your project. And include in .h #import <AudioToolbox/AudioToolbox.h>.
Remember to connect your button to buttonPressedWithSound through IBAction.
source
share