user1120133
user1120133

Reputation: 3234

Load audiofile array to collection view cells in sequence manner

I have loaded images and labels to custom collectionview cells in this method

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;


Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];

Giving the cells title based on actual NSIndexPath value in the same method

cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}", (long)indexPath.row, (long)indexPath.section];

Loading different images in each cell of the custom collection view cells in the same method

NSString *imageToLoad = [NSString stringWithFormat:@"%d.jpg", indexPath.row];

cell.image.image = [UIImage imageNamed:imageToLoad];

I want to load different audio files in each cell of the custom collection view cells in the same method

audioArray =[[NSArray alloc] initWithObjects:@"Theme1", @"Theme2", @"Theme3", @"Theme4", nil];

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:fileURL error:nil];

If i add indexPath.row below

NSString *filePath = [audioArray objectAtIndex:indexPath.row];

Then it always plays "Theme4" last audio file from within the array in all cells

And if i write 0

NSString *filePath = [audioArray objectAtIndex:0];

Then it plays always "Theme1" the very first audio file in all cells

How i can load different audio files in each cell of the custom collection view cells.

Thanks for help.

Upvotes: 0

Views: 200

Answers (1)

user1452248
user1452248

Reputation: 767

You should add these lines of code in

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath


audioArray =[[NSArray alloc] initWithObjects:@"Theme1", @"Theme2", @"Theme3", @"Theme4", nil];

NSString *filePath = [audioArray objectAtIndex:indexPath.row];

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

audioPlayer = [[AVAudioPlayer alloc]
           initWithContentsOfURL:fileURL error:nil];
}

rather than in

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;

Hope this helps.

Upvotes: 1

Related Questions