xcode - AVAudioPlayer 内存泄漏

标签 xcode memory avaudioplayer memory-leaks

我被困在一些与 AVAudioPlayer 相关的奇怪内存泄漏问题上,在尝试了所有想到的东西后我需要帮助。

这是问题的简短描述 - 代码紧随其后。
我初始化我的播放器并开始无限循环播放音轨(无限循环或一次播放并没有改变问题)。
音乐开始几秒钟后,我切换到另一个音轨,因此我创建了一个新播放器,初始化它,释放旧播放器(正在播放),然后将新播放器放置到位并播放。

在那个时间点(就在我调用新播放器之后 - [播放器播放])我得到了内存泄漏(3.5Kb)。

我尝试了以下方法:

  • 停止旧播放器然后释放它-无效
  • 播放指令后立即释放播放器 - 未开始播放
  • 两次释放老玩家-崩溃
  • 当我创建和播放第一个 Player 时不会发生内存泄漏!

  • 此外,在引用文献中确实说“播放”是异步的,因此可能会将引用计数增加 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/

    相关文章:

    swift - iOS VPN 连接阻止将 4G 连接切换到 WiFi 连接

    iphone - UITabBar 识别纵向或横向方向

    python模块内存使用

    ios - 快速恢复 AVAudioPlayer 中的声音

    ios - 锁屏上的 AVAudioPlayer

    iphone - Xcode 4 存档未显示在管理器中

    c++ - 如何执行从 char* 缓冲区加载到内存中的代码?

    c++ - Wt:1.5 GB 用于运行论坛(即使连接了单个用户)。正常吗?

    java - 如何在android中的项目单击中从 ListView 中获取歌曲

    xcode - UITableViewCell 自定义布局和边框 UIBubble