Swift:如何在中断时调用scheduleBuffer完成处理程序?

时间:2016-10-31 08:37:28

标签: ios swift avfoundation avaudioplayernode avaudiopcmbuffer

我有一个AVAudioPlayerNode,我正在使用以下方法安排大量缓冲区:

node.scheduleBuffer(buffer, at: nil, options: .interrupts, completionHandler: completeFunc)

但我有一点问题。如果我播放另一个缓冲区来中断当前正在播放的缓冲区,则仍会调用缓冲区中断的完成处理程序。我想这是有道理的,但我似乎无法找到一种方法来检查文件是否实际完成播放或是否被中断。有没有办法可以做到这一点?

任何答案都会有所帮助!

1 个答案:

答案 0 :(得分:1)

您将需要一个中断状态变量,该变量在完成处理程序中引用并由中断代码切换。下面是一些简写代码,对你如何循环缓冲区做出一些假设:

var node: AVAudioPlayerNode!
var loopingBuffers: [AVAudioPCMBuffer] = [buffer1, buffer2, buffer3]
var interruptBuffers = false // state variable to handle the interruption

func scheduleNextBuffer() {
    /* code to find the next buffer in the loopingBuffers queue */

    // assuming you have instantiated an AVAudioPlayerNode elsewhere
    node.scheduleBuffer(nextBuffer, completionHandler: bufferCompletion)
}

func bufferCompletion() {
    // check the state variable to make certain the completionHandler isn't being triggered by a scheduling interruption
    guard !interruptBuffers else { return }
    scheduleNextBuffer()
}

func interruptBuffers() {
    let newBuffers: [AVAudioPCMBuffer] = [buffer4, buffer5, buffer6]

    interruptBuffers = true

    node.scheduleBuffer(buffer4, at: nil, options: .interrupts, completionHandler: bufferCompletion)

    // cleanup your state and queue up your new buffers
    interruptBuffers = false
    loopingBuffers = newBuffers
}