views:

184

answers:

1

I am seeing in Instruments that when I play a sound via the standard "AddMusic" example method that Apple provides, it allocates 32kb of memory via the prepareToPlay call (which references the AudioToolBox framework's Cache_DataSource::ReadBytes function) each time a new player is allocated (i.e. each time a different sound is played). However, that cached data never gets released.

This obviously poses a huge problem if it doesn't get released and you have a lot of sound files to play, since it tends to keep allocating memory and eventually crashes if you have enough unique sound files (which I unfortunately do).

Have any of you run across this or what am I doing wrong in my code? I've had this issue for a while now and it's really bugging me since my code is verbatim of what Apple's is (I think).

How I call the function:

- (void)playOnce:(NSString *)aSound {

// Gets the file system path to the sound to play.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];  

// Converts the sound's file path to an NSURL object
NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = soundURL;
[soundURL release];

AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error:nil];  
self.theAudio = newAudio; // automatically retain audio and dealloc old file if new m4a file is loaded

[newAudio release]; // release the audio safely

// this is where the prior cached data never gets released
[theAudio prepareToPlay];

// set it up and play
[theAudio setNumberOfLoops:0];
[theAudio setVolume: volumeLevel];
[theAudio setDelegate: self];
[theAudio play];

}

and then theAudio gets released in the dealloc method of course.

+1  A: 

answer from another source named smasher:

You need a separate player for each sound with AVAudioPlayer; there's no choice. And the only way to free up the memory from the player is to release properly after it's done playing. Just calling "stop" keeps the player alive so you can play it again, and doesn't free any memory.

OpenAL has similar issues, you load a sound for each file; plus the most common implementation I've seen loads the entire file at once which is hard on memory.

You probably should release the player when it stops playing, or when you choose a new sound, or before a player for the new sound is created.

iWasRobbed