简体   繁体   中英

Play a sound file when tapping table cell

What I'm trying to do when a user taps a cell I want it to play a sound. So far from what I have searched it has to be implemented in:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];

}

I just don't know the best way to call it. Any help would be appreciated.

make a class variable for the audioPlayer:

AVAudioPlayer *cellTapSound;

in viewDidLoad (or viewWillAppear):

cellTapSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"cellTapSound" withExtension:@"mp3"] error:nil];

[cellTapSound prepareToPlay];

in didSelectRowAtIndexPath:

// this line will rewind the player each time you tap again before it ends playing 
// you can tap as fast as you can and play some sort of a tune
// must have some fun while testing

if (cellTapSound.isPlaying) [cellTapSound setCurrentTime:0.0]; 

[cellTapSound play];

do not forget to:

  • add AVFoundation.framework to your project
  • #import <AVFoundation/AVFoundation.h>
  • Drag&Drop audio file into your project bundle and update the URL for AVAudioPlayer init
  • read about AVAudioPlayer to find out what else you can do with it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM