ios – 使用后删除AVAudioPlayerNode会导致崩溃

我正在使用AVAudioEngine播放声音文件并将输出记录到文件中.我有很多音效文件,每个都是通过点按一个按钮播放的.要播放该文件,我创建一个AVAudioPlayerNode并将其连接到引擎.文件播放后,我尝试断开/分离completionHandler闭包中的节点,以释放内存.如果我不删除节点,我将继续添加新节点和引擎的新连接.

但是,下次我尝试播放文件时,应用程序就会冻结.这是我的代码:

let url = NSBundle.mainBundle().URLForResource(name, withExtension: "wav")!
let audioPlayerFile = try AVAudioFile(forReading: url)
let playerNode = AVAudioPlayerNode()
self.engine.attachNode(playerNode)
self.engine.connect(playerNode, to: self.engine.mainMixerNode, format: audioPlayerFile.processingFormat)
playerNode.scheduleFile(audioPlayerFile, atTime: nil, completionHandler: { () -> Void in
    self.engine.disconnectNodeOutput(playerNode)
    self.engine.detachNode(playerNode)
})
playerNode.play()

在录制的同时,实现这样的功能的最佳方法是什么,即播放多个文件,可能相互重叠?

最佳答案 我有类似的问题.我发现在后台线程上分离节点可以防止应用程序冻结.

    playerNode.scheduleBuffer(buffer, atTime: nil, options: nil) { () -> Void in
        self.detach(playerNode)
    }

这是方法:

    func detach(player: AVAudioPlayerNode) {
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0)) { () -> Void in
            self.engine.detachNode(player)
    }

但是,我仍然不确定这本身就是一个解决方案,因为这些后台线程可能在我不知情的情况下无限旋转.

点赞