AVAudioPlayer not unloading cached memory after each new allocation
- by Rob
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.