Search code examples
objective-cnsarraytableviewavfoundationavplayer

Objective-C How to play a sound when a cell's button is tapped?


I have a button on each cell and while the button is tapped I want to play different audio file from array for each cell.

I don't know how to implement an array of sounds/audio files for my table view cells.

I have a button outlet and action on my UITableViewCell. But I am not sure how to initialise my AVaudioplayer in tableview.m specifically in:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell22";

Below I've inserted an image of the project I want to achieve. image1


Solution

  • check now i updated code :its playing sound

    1.create property in .h or .m file for ur AVAudioPlayer . like

    @property (strong, nonatomic) AVAudioPlayer *audioPlayer;
    
    1. declare <AVAudioPlayerDelegate> in .m file and

    @synthesize audioPlayer;

    3.implement this code in :

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

     yourSoundArray=[NSArray arrayWithObjects:@"sss",@"sss",@"sss",@"sss",@"sss",@"sss", nil];//dont include formate type
    
    
       NSString *audioPath = [[NSBundle mainBundle] pathForResource: [yourSoundArray objectAtIndex:indexPath.row] ofType:@"mp3"];
                        NSLog(@"%@",audioPath);
    
                        NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    
                        NSError *audioError = [[NSError alloc] init];
                        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&audioError];
                        audioPlayer.delegate=self;
    
                     if (!audioError) {
                            NSLog(@"playing!");
                            audioPlayer play];
                      }
                        else {
                              NSLog(@"Error!");
                        }
    

    4.

    -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
    {
        NSLog(@"%d",playing the audio);
    }
    

    happy coding its working please check :