我在 Instruments 中看到,当我通过 Apple 提供的标准“AddMusic”示例方法播放声音时,每次分配新播放器时prepareToPlay
(即每次播放不同的声音)。但是,缓存的数据永远不会被释放。AudioToolBox
Cache_DataSource::ReadBytes
如果它没有被释放并且你有很多声音文件要播放,这显然会带来一个巨大的问题,因为如果你有足够的独特声音文件(不幸的是我这样做),它往往会不断分配内存并最终崩溃。
你们中是否有人遇到过这个问题,或者我在代码中做错了什么?这个问题我已经有一段时间了,这真的让我很烦恼,因为我的代码是苹果的逐字记录(我认为)。
我如何调用函数:
- (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];
}
然后在当然的方法中theAudio
被释放。dealloc