Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm using the following code in my viewDidLoad to load a sound:

NSURL * url = [NSURL fileURLWithPath:
   [NSString stringWithFormat:@"%@/Moto - Hit Sound.mp3",
   [[NSBundle mainBundle] resourcePath]]];
NSError * error;
hitSoundPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
hitSoundPlayer.numberOfLoops = 0;

Then I'm using this in a void method to play the sound:

if(CGRectIntersectsRect(main.frame, enemy1.frame)){
    [hitSoundPlayer play];
}

This does seem to work, however the first time the sound is played there is a lot of lag and the game stops temporarily. I'm using this same method for when in an IBAction and it works fine, it must be the fact that it's also detecting a collision that makes the sound lag. If I want to be able to play sounds quickly and on the spot without any sort of lag am I doing the right thing? Do I want to use another method? I'm not using any frameworks like cocos2d. If you need to see any more code just ask.

share|improve this question

1 Answer 1

Try calling prepareToPlay after AVAudioPlayer is initialised.

[hitSoundPlayer prepareToPlay];

Also, if AVAudioPlayer is not the first initialised it might not be using the hardware to play the audio?

share|improve this answer
    
+1 Because whatever else is contributing, part of this likely has to do with decoder delay since the file is an mp3, and it looks like the prepareToPlay message prepares the first frame of audio. Sound effects are usually stored in a format that takes little or no work to decode, or else decoded at load time and stored uncompressed in memory so they can be played instantly. –  michael.bartnett Apr 24 '13 at 20:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.