Connect AVAudioInputNode to AVAudioUnitEffect using AVAudioEngine

只愿长相守 提交于 2019-12-24 02:07:50

问题


I want to process the audio from my device's built-in microphone (AVAudioInputNode) with an audio unit effect (AVAudioUnitEffect). For my example, I'm using AVAudioUnitReverb. Connecting AVAudioUnitReverb is causing the application to crash.

import UIKit
import AVFoundation

class ViewController: UIViewController {

    let audioEngine = AVAudioEngine()
    let unitReverb = AVAudioUnitReverb()

    var inputNode: AVAudioInputNode!

    override func viewDidLoad() {
        super.viewDidLoad()

        inputNode = audioEngine.inputNode
        audioEngine.attachNode(unitReverb)

        let inputFormat = inputNode.inputFormatForBus(0)
        audioEngine.connect(inputNode, to: unitReverb, format: inputFormat)

        // This line is crashing the application!
        // With this error "AVAudioNode.mm:521: AUSetFormat: error -10868"
        audioEngine.connect(unitReverb, to: audioEngine.outputNode, format: inputFormat)

        audioEngine.startAndReturnError(nil)
    }

}

I have no issues if I bypass the reverb and connect inputNode directly to audioEngine.outputNode, but then I have no reverb:

audioEngine.connect(inputNode, to: audioEngine.outputNode, format: inputFormat)

What am I doing wrong?

Update

I inadvertently discovered that the above code only crashes the application when my Apple EarPods with Remote and Mic are connected. When using the device's built-in microphone, I have no issues. So, why does the mic on my headphones crash the application, but only when using an AVAudioUnitEffect?


回答1:


After some trial and error, changing the format arguments seems to have resolved this issue. The revised code looks like this:

let format = unitReverb.inputFormatForBus(0)
audioEngine.connect(inputNode, to: unitReverb, format: format)
audioEngine.connect(unitReverb, to: audioEngine.outputNode, format: format)


来源:https://stackoverflow.com/questions/28331461/connect-avaudioinputnode-to-avaudiouniteffect-using-avaudioengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!