【问题标题】:AVAudioPlayer preloaded sound leaks from memoryAVAudioPlayer 预加载的声音从内存泄漏
【发布时间】:2015-09-21 15:23:45
【问题描述】:

我有一个 AVAudioPlayer 实例,它使用audioPlayer.prepareToPlay() 将声音加载到内存中,然后开始播放。我有一个问题,在进入后台大约十分钟后,它从内存中泄漏,我没有做好准备。在那喂食时间之后,我无法再次运行prepareToPlay()。如何将预加载的声音长期留在记忆中?我正在准备在applicationDidFinishLaunchingWithOptionsmethod 中播放声音:

let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(dispatchQueue, {[weak self] in
        var audioSessionError: NSError?

        let audioSession = AVAudioSession.sharedInstance()
        NSNotificationCenter.defaultCenter().addObserver(self!, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: nil)
        audioSession.setActive(true, error: nil)

        if (audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError)) {
            println("Successfully set the audio session")
        } else {
            println("Could not set the audio session")
        }

        let filePath = NSBundle.mainBundle().pathForResource("sound", ofType:"mp3")
        let fileData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil)
        var error:NSError?

        self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)

        self!.audioPlayer?.numberOfLoops = -1

        self!.audioPlayer?.delegate = self

        if (self?.audioPlayer?.prepareToPlay() != false) {
            println("Successfully prepared for playing")
        } else {
            println("Failed to prepare for playing")
        }
    })

然后在didReceiveRemoteNotification 我试图在后台播放它:self.audioPlayer?.play(),它返回true。可能它可以工作,但大约 10 - 20 分钟后它不起作用。请注意,.play() 现在返回false

  1. 禁用 ARC(自动引用计数)以手动释放和解除 audioPlayer 是否有意义?

  2. 也许我需要使用较低级别的 API,例如 OpenAL?但是我不会使用它,因为它在 iOS 9 中已被弃用,以后我需要在没有 OpenAL 的情况下重写它。

  3. 还有什么想法吗?也许我需要将Audio UnitsRemoteIO 一起使用?如果可行,请提供一些示例。

  4. 也许有像 ObjectAL 这样的第三方框架 - OpenAL 的简单实现。据我所知,它在 iOS 9 中可用。

这些方法只是我的假设。但他们的主要问题仍然是相同的:这些方法会在后台工作吗?

【问题讨论】:

标签: ios memory-management memory-leaks background avaudioplayer


【解决方案1】:

您应该禁用 ARC。当你进入背景时,如果你不使用它,它就会被释放。在 Swift 中创建 AVAudioPlayer 作为Unmanaged<T> 对象。

【讨论】:

    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多