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

1

16

I am trying to create a speech to text function and I am getting the error:

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

guard let inputNode = audioEngine.inputNode else {
        fatalError("Audio engine has no input node")
    }
Passel answered 24/9, 2017 at 16:38 Comment(3)
I have exactly the opposite problem, in my case the inputNode is optional even though the documentation says otherwise.Malonis
How did you achieve that it is not nil? Do you use Swift 4? Which "AV" framework do you link into your project?Malonis
this is straight from Apple's sample code and it doesn't appear to workPasteup
A
14

AVAudioEngine's inputNode property is not an optional. The Audio Engine creates a singleton on demand when inputNode is first accessed. It cannot be nil and because of that the guard does not make sense.

So, just remove the guard and use audioEngine.inputNode as it is. It cannot be nil.

You still have to make sure that the inputNode is connected to something before using it:

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.

(from Apple's Documentation)

Agosto answered 24/9, 2017 at 18:14 Comment(3)
What should we do when the frequency or channel count are zero? I have encountered this situation a few times and only device restart fixed it...Malonis
anyone able to fix the problem what @Malonis have mentioned?Counterclockwise
Worth noting it actually used to be optional prior to iOS 11.Ault

© 2022 - 2024 — McMap. All rights reserved.