Search code examples
iphoneioscocos2d-iphonesimpleaudioengine

SimpleAudioEngine takes time to play sound


I am using SimpleAudioEngine to play sounds in my cocos2D application. I have a situation of continues shooting bullets on tapping on a button and playing a sound whenever a bullet is shot. When i continuously tap the shoot button sometimes, game scene jerks. This started happening when i integrated the sounds.

This is the code i use on button tap :

-(void)rocketButtonTapped:(id)sender
{
  [[SimpleAudioEngine sharedEngine] playEffect:@"rocket_fired.wav"];
  NSLog(@"Pencil Rocket");
  if(int_pencilRocketTagCount>=220)
  {
    int_pencilRocketTagCount=215;
  }
  [self performSelector:@selector(shootPencilRocket)];  
}

Please suggest me a way out... Thanks in advance..


Solution

  • Before the game starts, do this:

    [[SimpleAudioEngine sharedEngine] preloadEffect:@"rocket_fired.wav"];
    

    This loads the effect into memory. If this doesn't fix the problem then the issue may be elsewhere. For example too many sound effects playing all at once if the rocket fire sound is several seconds long this could be an issue. Also continuous logging to Debug Console via NSLog or CCLOG is slow and can easily cause framerate to drop.

    It might also help to reduce the sound quality. A sample rate of 22 or even 11 kHz is enough for (short) sound effects, 44 kHz is wasteful as it increases the memory usage 2 or 4 times respectively. If the effect file uses stereo channels, convert it to mono to cut the size in half. The less memory the effect uses, the less it strains the hardware playing it.