如何释放AudioFileReadPacketData使用的内存--Xcode显示仍在使用的内存

时间:2014-09-27 16:16:44

标签: ios objective-c c core-audio audiounit

我通过传递MPMediaItem对象,使用以下方法将音频文件读入RAM。但是,每次调用它时,函数的开头都应该释放用于前一个音频文件的内存,而且它没有,即Xcode显示每次调用函数时内存使用量都会不断增加,最终操作系统内存不足。

我做了什么明显的错误吗?

注意:以下功能是我使用audioData ivar

的唯一地方

Memory allocation summary in Instruments

The same audio file cached in memory by below function

void *audioData;

- (void)playItem:(MPMediaItem *)mediaItem
{
   if (audioData != NULL) {
       NSLog(@"audio data pointer not empty");
       free (audioData);
   }

   // open audio file
   AudioFileID audioFileID;
   NSURL *mediaItemURL = [mediaItem valueForProperty:MPMediaItemPropertyAssetURL];

   OSErr err;
   err = AudioFileOpenURL((__bridge CFURLRef)mediaItemURL,
                          kAudioFileReadPermission,
                          0,
                          &audioFileID);
   NSAssert(err == noErr, @"Couldn't open audio file...");

   // read audio file properties and malloc audioData property
   UInt32 audioDataPacketCount;
   UInt32 audioDataPacketCountSize = sizeof(audioDataPacketCount);
   err = AudioFileGetProperty(audioFileID,
                              kAudioFilePropertyAudioDataPacketCount,
                              &audioDataPacketCountSize,
                              &audioDataPacketCount);
   NSAssert(err == noErr, @"Couldn't read audio file properties...");

   UInt32 audioDataByteCount;
   UInt32 audioDataByteCountSize = sizeof(audioDataByteCount);
   err = AudioFileGetProperty(audioFileID,
                              kAudioFilePropertyAudioDataByteCount,
                              &audioDataByteCountSize,
                              &audioDataByteCount);
   NSAssert(err == noErr, @"Couldn't read audio file properties...");
   audioData = malloc(audioDataByteCount);

   // read audio file packets
   err = AudioFileReadPacketData(audioFileID,
                                 false,
                                 &audioDataByteCount,
                                 NULL,
                                 0,
                                 &audioDataPacketCount,
                                 audioData);
   NSAssert(err == noErr, @"Couldn't read audio file to memory...");

}
编辑:我使用相同的代码结构并使用ExtAudioFileRead函数读取音频文件数据,并且内存释放并按照所谓的方式重新分配。这可能与我如何使用AudioFileReadPacketData函数= /

有关

1 个答案:

答案 0 :(得分:0)

在释放AudioFileClose资源之前,您需要致电AudioFileID

否则,AudioFile会保留对音频数据无效指针的引用,并且无法释放内存。

if (audioData != NULL) {
   NSLog(@"audio data pointer not empty");
   AudioFileClose(audioFileID);  // <- missing call
   free (audioData);
}