How can I play a sound by touching a UICollectionViewCell once, and stop the same sound by touching the same UICollectionViewCell again, using AVAudioPlayer?
My code plays the sound correctly, but it won't stop it when I press the cell, it just starts the loop from the beginning. My current code is the following:
// Sound
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// Loop
int loopOrNot;
BOOL playing = 0;
if ([loopArray containsObject:saveFavorite]) // YES
{
loopOrNot = -1;
} else {
loopOrNot = 0;
}
// Play soundeffects
if (playing==NO) {
// Init audio with playback capability
// Play sound even in silent mode
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.wav", [[NSBundle mainBundle] resourcePath], [mainArray objectAtIndex:indexPath.row]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = loopOrNot;
if (audioPlayer == nil) {
// NSLog([error description]);
}
else {
[audioPlayer play];
}
playing=YES;
}
else if(playing==YES){
[audioPlayer stop];
playing=NO;
}
}