AVAudioPlayer预装了内存中的声音泄漏

Nik*_*nov 12 memory-leaks memory-management background avaudioplayer ios

我有一个AVAudioPlayer实例,它在内存中加载声音audioPlayer.prepareToPlay(),然后在几次开始播放之后.我有一个问题,在进入背景后大约十分钟内,它从记忆中泄漏,我没有准备好.在那个喂食时间之后,我没有能力prepareToPlay()再次跑步.如何长时间将预装的声音留在内存中?我准备声音播放applicationDidFinishLaunchingWithOptions方法:

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")
        }
    })
Run Code Online (Sandbox Code Playgroud)

然后在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中使用.

这些方法只是我的假设.但他们的主要问题仍然是相同的:这些方法是否可以从后台运作?

小智 2

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