使用 AVAudioEngine 从内存中播放立体声音频缓冲区

Playing a stereo audio buffer from memory with AVAudioEngine

我正在尝试在我的 iOS 应用程序中从内存(而不是文件)播放 stereo 音频缓冲区,但是当我尝试附加AVAudioPlayerNode 'playerNode' 到 AVAudioEngine 'audioEngine'。我得到的错误代码如下:

Thread 1: Exception: "required condition is false: _outputFormat.channelCount == buffer.format.channelCount"

我不知道这是不是因为我声明 AVAudioEngine、AVAudioPlayerNode 的方式,我生成的缓冲区是否有问题,或者我是否错误地附加了节点(或其他原因) !)。我觉得这与我创建新缓冲区的方式有关。我正在尝试从两个单独的 'mono' 数组制作立体声缓冲区,也许它的格式不正确。

我已经声明了音频引擎:AVAudioEngine!和播放器节点:AVAudioPlayerNode!全球:

var audioEngine: AVAudioEngine!
var playerNode: AVAudioPlayerNode!

然后我加载一个 mono source 音频文件,我的应用程序将要处理(该文件中的数据不会被播放,它将被加载到一个数组中,处理并然后加载到缓冲区):

    // Read audio file
    let audioFileFormat = audioFile.processingFormat
    let frameCount = UInt32(audioFile.length)
    let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFileFormat, frameCapacity: frameCount)!
    
    // Read audio data into buffer
    do {
        try audioFile.read(into: audioBuffer)
    } catch let error {
        print(error.localizedDescription)
    }
    // Convert buffer to array of floats
    let input: [Float] = Array(UnsafeBufferPointer(start: audioBuffer.floatChannelData![0], count: Int(audioBuffer.frameLength)))

然后将数组发送到卷积函数两次,每次returns一个新数组。这是因为单声道源文件需要变成立体声音频缓冲区:

    maxSignalLength = input.count + 256
    let leftAudioArray: [Float] = convolve(inputAudio: input, impulse: normalisedLeftImpulse)
    let rightAudioArray: [Float] = convolve(inputAudio: input, impulse: normalisedRightImpulse)

maxSignalLength 变量当前是输入信号的长度 + 与之卷积的脉冲响应 (normalisedImpulseResponse) 的长度,目前为 256。这将在某个时候成为合适的变量。

然后我声明并加载新缓冲区及其格式,我感觉错误就在附近某处,因为这将是播放的缓冲区:

    let bufferFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: hrtfSampleRate, channels: 2, interleaved: false)!
    let outputBuffer = AVAudioPCMBuffer(pcmFormat: bufferFormat, frameCapacity: AVAudioFrameCount(maxSignalLength))!

请注意,我不是在创建交错缓冲区,而是按如下方式将立体声音频数据加载到缓冲区(我认为这也可能是错误的):

        for ch in 0 ..< 2 {
        for i in 0 ..< maxSignalLength {
            
            var val: Float!
            
            if ch == 0 { // Left
                
                val = leftAudioArray[i]
                // Limit
                if val > 1 {
                    val = 1
                }
                if val < -1 {
                    val = -1
                }
                
            } else if ch == 1 { // Right
                
                val = rightAudioArray[i]
                // Limit
                if val < 1 {
                    val = 1
                }
                if val < -1 {
                    val = -1
                }
            }
            
            outputBuffer.floatChannelData![ch][i] = val
        }
    }

音频也被限制在 -1 到 1 之间的值。

然后我终于(试图)将缓冲区加载到音频节点,将音频节点附加到音频引擎,启动音频引擎然后播放节点。

    let frameCapacity = AVAudioFramePosition(outputBuffer.frameCapacity)
    let frameLength = outputBuffer.frameLength
    
    playerNode.scheduleBuffer(outputBuffer, at: nil, options: AVAudioPlayerNodeBufferOptions.interrupts, completionHandler: nil)
    playerNode.prepare(withFrameCount: frameLength)
    let time = AVAudioTime(sampleTime: frameCapacity, atRate: hrtfSampleRate)
    
    audioEngine.attach(playerNode)
    audioEngine.connect(playerNode, to: audioEngine.mainMixerNode, format: outputBuffer.format)
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch let error {
        print(error.localizedDescription)
    }
    
    playerNode.play(at: time)

我在运行时得到的错误是:

AVAEInternal.h:76    required condition is false: [AVAudioPlayerNode.mm:712:ScheduleBuffer: (_outputFormat.channelCount == buffer.format.channelCount)]

不显示发生此错误的行。我已经坚持了一段时间,并尝试了很多不同的东西,但似乎没有关于从内存中播放音频而不是从我能找到的 AVAudioEngine 文件中播放音频的非常明确的信息。任何帮助将不胜感激。

谢谢!

编辑 #1: 更好的标题

编辑#2: 更新 - 我发现了为什么会出现错误。这似乎是在将播放器节点附加到音频引擎之前设置播放器节点引起的。交换顺序阻止程序崩溃并抛出错误:

    let frameCapacity = AVAudioFramePosition(outputBuffer.frameCapacity)
    let frameLength = outputBuffer.frameLength
    
    audioEngine.attach(playerNode)
    audioEngine.connect(playerNode, to: audioEngine.mainMixerNode, format: outputBuffer.format)
    audioEngine.prepare()
    
    playerNode.scheduleBuffer(outputBuffer, at: nil, options: AVAudioPlayerNodeBufferOptions.interrupts, completionHandler: nil)
    playerNode.prepare(withFrameCount: frameLength)
    let time = AVAudioTime(sampleTime: frameCapacity, atRate: hrtfSampleRate)
    
    do {
        try audioEngine.start()
    } catch let error {
        print(error.localizedDescription)
    }

    playerNode.play(at: time)

但是,我没有任何声音。在使用与用于输入信号的方法相同的方法创建 outputBuffer 的浮点数数组并使用断点查看其内容后,它似乎是空的,因此我也必须错误地将数据存储到 outputBuffer。

您可能没有正确地创建和填充缓冲区。尝试这样做:

let fileURL = Bundle.main.url(forResource: "my_file", withExtension: "aiff")!
let file = try! AVAudioFile(forReading: fileURL)
let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: UInt32(file.length))!
try! file.read(into: buffer)

我已经解决了这个问题!

我尝试了很多解决方案并最终完全 re-writing 我的应用程序的音频引擎部分,我现在在 ViewController class 中声明了 AVAudioEngine 和 AVAudioPlayerNode 作为以下:

class ViewController: UIViewController {

var audioEngine: AVAudioEngine = AVAudioEngine()
var playerNode: AVAudioPlayerNode = AVAudioPlayerNode()

...

我仍然不清楚是在全局声明这些变量还是在 iOS 中声明为 class 变量更好,但是我可以确认我的应用程序正在使用 [=37] 中声明的这些变量播放音频=] class。我知道它们不应该在函数中声明为

但是,直到我将 AVAudioPCMBuffer.frameLength 设置为 frameCapacity。

之前我仍然没有得到任何音频输出。

关于从浮点数组创建新的 AVAudioPCMBuffer,我在网上找到的信息很少,但这似乎是我需要做的让我的 outputBuffer 可播放的缺失步骤。在我设置之前,它默认为 0。

AVAudioFormat class 声明中不需要 frameLength 成员。但这很重要,我的缓冲区在我手动设置之前无法播放,并且在 class 实例声明之后:

let bufferFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: hrtfSampleRate, channels: 2, interleaved: false)!
let frameCapacity = UInt32(audioFile.length)
guard let outputBuffer = AVAudioPCMBuffer(pcmFormat: bufferFormat, frameCapacity: frameCapacity) else {
    fatalError("Could not create output buffer.")
}
outputBuffer.frameLength = frameCapacity // Important!

这花了很长时间才找到,希望这对以后的其他人有所帮助。