iPhone - How to play a sound on button touch?
I'm trying to make a button play a sound upon touching the button. I can get the sound to play with the Touch Up Inside option but that's not what I'm looking for because the sound only plays after the button is released.
I've tried to use touchesBegan to play the sound upon touching the button but it doesn't seem to work. Any ideas why?
Thanks
My code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
[super touchesBegan:touches withEvent:event];
if([touch view] == doneButton) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"click" ofType:@"caf"];
AVAudioPlayer* clickAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
开发者_Python百科
clickAudio.delegate=self;
[clickAudio play];
}
}
Use a UIButton
. Call -play
on touch down and call -stop
on touch up.
精彩评论