Reputation: 53
I want to create a button and make it play a sound when it is touched. So far, I can make the button, but I'm having trouble making it play the sound. Here's what I have:
//loads wav file into SoundID
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID);
//creates button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[scrollview addSubview:button]
//this line is the problem
[button addTarget:self action:@selector(AudioServicesPlaySystemSound((SoundID)) forControlEvents:UIControlEventTouchDown];
For some reason, xcode won't let me play a sound directly from the button click. How can I make touching the button play the SoundID?
Upvotes: 1
Views: 3108
Reputation: 1878
Here is your edited answer. Hope this helps:
-(void)viewDidLoad {
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID);
//creates button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[scrollview addSubview:button]
//this line was causing problem
[button addTarget:self action:@selector(playSound:) forControlEvents:UIControlEventTouchDown];
}
-(void)playSound:(id)sender{
AudioServicesPlaySystemSound((SoundID)
}
Upvotes: 0
Reputation: 2308
Your button action method must have the following signature:
-(void)buttonActionMethod:(id)inSender
That means you cannot call a system method directly. For what you are trying to do, I would suggest this method:
//loads wav file into SoundID
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"medic_taunts01" ofType:@"wav"]];
SystemSoundID soundID
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &soundID );
self.SoundID = soundID;
//creates button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[scrollview addSubview:button]
//this line is the problem
[button addTarget:self action:@selector(playButtonSound:) forControlEvents:UIControlEventTouchDown];
Note the conversion of SoundID
to a property (I trust you know how to make those). Then define this method:
-(void)playButtonSound:(id)inSender {
AudioServicesPlaySystemSound(self.SoundID);
}
Of course, if you have more than one button, each with different sounds, you will need to get a little more creative here with mapping sound IDs to the button.
Upvotes: 1