我被困在一些与 AVAudioPlayer 相关的奇怪内存泄漏问题上,在尝试了所有想到的东西后我需要帮助。
这是问题的简短描述 - 代码紧随其后。
我初始化我的播放器并开始无限循环播放音轨(无限循环或一次播放并没有改变问题)。
音乐开始几秒钟后,我切换到另一个音轨,因此我创建了一个新播放器,初始化它,释放旧播放器(正在播放),然后将新播放器放置到位并播放。
在那个时间点(就在我调用新播放器之后 - [播放器播放])我得到了内存泄漏(3.5Kb)。
我尝试了以下方法:
此外,在引用文献中确实说“播放”是异步的,因此可能会将引用计数增加 1,但在这种情况下,为什么 [Player stop] 没有帮助?
谢谢,
以下是有关我如何使用它的代码的一些部分:
- (void) loadAndActivateAudioFunction {
NSBundle *mainBundle = [NSBundle mainBundle];
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:[mainBundle pathForResource: Name ofType: Type]];
AVAudioPlayer *player = [(AVAudioPlayer*) [AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
if (!player) {
DebugLog(@"Audio Load Error: no Player: %@", [error localizedDescription]);
DuringAudioPrep = false;
return;
}
[self lock];
[self setAudioPlayer: player];
[self ActivateAudioFunction];
[self unlock];
}
- (void) setAudioPlayer : (AVAudioPlayer *) player {
if (Player)
{
if ([Player isPlaying] || Repeat) // The indication was off???
[Player stop];
[Player release];
}
Player = player;
}
- (void) ActivateAudioFunction {
[Player setVolume: Volume];
[Player setNumberOfLoops: Repeat];
[Player play];
DuringAudioPrep = false;
}
最佳答案
这是创建 AVAudioPlayer 而不会导致内存泄漏的方法。 See this page for explaination .
我已经在我的应用程序中确认这消除了我的 AVAudioPlayer 泄漏 100%。
- (AVAudioPlayer *)audioPlayerWithContentsOfFile:(NSString *)path {
NSData *audioData = [NSData dataWithContentsOfFile:path];
AVAudioPlayer *player = [AVAudioPlayer alloc];
if([player initWithData:audioData error:NULL]) {
[player autorelease];
} else {
[player release];
player = nil;
}
return player;
}
关于xcode - AVAudioPlayer 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1352588/