I have this code:
int ran = 1 + arc4random() % 18;
NSString *soundFileIs=[NSString stringWithFormat:@"ton%i.mp3",ran];
NSString *paths = [[NSBundle mainBundle] resourcePath];
NSString *audioFile = [paths stringByAppendingPathComponent:soundFileIs];
NSData *cdata =[NSData dataWithContentsOfFile:audioFile];
audioPlayer = [[AVAudioPlayer alloc] initWithData:cdata error:nil];
audioPlayer.delegate = self;
[audioPlayer play];
When I shake device, it plays random my 18 sounds. How can I make to stop previously playing sound, and play next sound? Everything works great, just I hear 1st sound when I shake for first time, when I shake 2nd time, i hear 1st and 2nd sound playing if my 1st sound didn’t stop play. Thank you.
Before playing anything, check to see if it’s already playing and call stop. Your code will then be: