(Swift) 条件绑定的初始化器必须是 Optional 类型,而不是 'AVAudioInputNode'

(Swift) Initializer for conditional binding must have Optional type, not 'AVAudioInputNode'

我正在尝试创建语音转文本功能,但出现错误:

Initializer for conditional binding must have Optional type, not 'AVAudioInputNode'

guard let inputNode = audioEngine.inputNode else {
        fatalError("Audio engine has no input node")
    }

AVAudioEngineinputNode属性不是可选的。首次访问 inputNode 时,音频引擎会根据需要创建一个单例。它不能为零,因此守卫没有意义。

所以,只需移除防护并按原样使用 audioEngine.inputNode。不能是 nil.

您仍然需要确保 inputNode 在使用前已连接到某物:

Check the input format of input node (specifically, the hardware format) for a non-zero sample rate and channel count to see if input is enabled.

(来自 Apple 文档)