如何通过触摸一次UICollectionViewCell播放声音,并使用AVAudioPlayer再次触摸相同的UICollectionViewCell来停止相同的声音?使用相同的按钮播放和停止声音 - AVAudioPlayer
我的代码正确播放声音,但当按下单元格时它不会停止它,它只是从一开始就启动循环。我当前的代码如下:
// 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;
}
}