I am developing an application where the user can tap multiple hit areas which produces sounds.
But the result is a little laggy, when multiple sounds start at the same time, the sounds are played with an ugly delay.
I am using AVAudioPlayer instances for each sound.
Is there a better way to play sounds and prevent this lag?
Here’s the code:
#import "MBImageView.h"
#import <AVFoundation/AVFoundation.h>
@implementation MBImageView
-(void)awakeFromNib
{
NSURL* audioFile = [NSURL fileURLWithPath[[NSBundlemainBundle] pathForResource:@"shaker"
ofType:@"caf"]];
AudioServicesCreateSystemSoundID((CFURLRef)audioFile, &shortSound);
}
- (id)initWithImage:(UIImage *)image{
return self;
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
AudioServicesPlaySystemSound(shortSound);
}
@end
Regards.
Most of these sounds (AVAudioPlayer and AudioServices) are playing after your runloop ends. That is, you say play and they get queued for playing, and they don’t start playing immediately.
If you want lag free sound, you use Audio Unit:
You may also want to look at Audio Toolbox: