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")
    }
Niall Kiddle
  • 1,477
  • 1
  • 16
  • 35
  • I have exactly the opposite problem, in my case the `inputNode` is optional even though the documentation says otherwise. – shelll Sep 29 '17 at 08:49
  • How did you achieve that it is not nil? Do you use Swift 4? Which "AV" framework do you link into your project? – shelll Sep 29 '17 at 09:00
  • this is straight from Apple's sample code and it doesn't appear to work – user798719 Jan 17 '18 at 07:52

1 Answers1

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)

joern
  • 27,354
  • 7
  • 90
  • 105
  • 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... – shelll Sep 29 '17 at 08:49
  • anyone able to fix the problem what @shelll have mentioned? – Tarun Nov 06 '17 at 18:27
  • 1
    Worth noting it actually used to be optional prior to iOS 11. – shim Apr 13 '18 at 05:06