1

我在 Instruments 中看到,当我通过 Apple 提供的标准“AddMusic”示例方法播放声音时,每次分配新播放器时prepareToPlay(即每次播放不同的声音)。但是,缓存的数据永远不会被释放。AudioToolBoxCache_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

4

1 回答 1

2

来自另一个名为粉碎机的来源的回答:

您需要使用 AVAudioPlayer 为每个声音单独播放器;没有选择。释放播放器内存的唯一方法是在播放完毕后正确释放。只需调用“停止”即可使播放器保持活动状态,这样您就可以再次播放它,并且不会释放任何内存。

OpenAL 也有类似的问题,你为每个文件加载一个声音;加上我见过的最常见的实现一次加载整个文件,这在内存上很困难。

您可能应该在播放器停止播放时、在您选择新声音时或在创建新声音的播放器之前释放播放器。

于 2010-05-05T11:13:09.787 回答