如何通過觸摸一次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;
}
}