views:

626

answers:

3

Hello,

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.

+1  A: 

If they're short sounds that you don't mind loading into memory, the C-based System Sound Services might suit you better.

invalidname
Yes, I have a bunch of small sounds.I have already tried System Services, the same problem with delay persists. PS: I am testing directly into an iPhone 3Gs.
goo
+4  A: 

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:

To provide lowest latency audio, especially when doing simultaneous input and output (such as for a VoIP application), use the I/O unit or the Voice Processing I/O unit. See “Audio Unit Support in iPhone OS.”

You may also want to look at Audio Toolbox:

Use the Audio Toolbox framework to play audio with synchronization capabilities, access packets of incoming audio, parse audio streams, convert audio formats, and record audio with access to individual packets. For details, see Audio Toolbox Framework Reference and the SpeakHere sample code project.

mahboudz
Thank you mahboudz, but I think my sounds are not delaying for any reason like that. I think (and I am testing it right now) it is the response from the touch that is delaying.
goo
You should be able to step through the code and see when the sound actually starts playing. If your code doesn't return fast enough to the iPhone OS, after handling the touch where the sound is played, then the sound isn't playing until then either.
mahboudz
A: 

I've used the SoundEffect class in Audio Toolbox with good results. My short sounds play with no delay.

Also one other thing to consider with audio delays; make sure your audio files has no "whitespace" before the actual sound - I beat my head into a wall once looking for the sound delay, only to find it in the actual audio file itself.

Hope this helps.

Mike W