gcstr
gcstr

Reputation: 1547

iPhone Sounds and delay

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.

Upvotes: 2

Views: 2037

Answers (3)

Mike W
Mike W

Reputation: 4428

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.

Upvotes: 0

mahboudz
mahboudz

Reputation: 39376

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.

Upvotes: 6

invalidname
invalidname

Reputation: 3185

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

Upvotes: 1

Related Questions