I am new to Swift and trying to implement the audioEngine for a microphone in order to record.
At one point I declare the inputNode (microphone) with the statement:
print("before input node")
guard let inputNode = audioEngine.inputNode else {
fatalError("Audio engine has no input node")
}
print("after check of input node")
Stepping through the code in the debugger, an exception occurs at runtime in the course of the guard let inputNode
statement. The code prints "before inputNode
" but never prints the fatalError
or the "after check
" lines
I was under the impression that a guard statement in Swift detects a nil value thereby avoiding a crash but that is not occurring in this case.
Would appreciate any suggestions on what might be going wrong.
For reference, prior to this point in the method the following code runs without issue:
public fund startRecording()
if recognitionTask != nil {
recognitionTask?.cancel()
recognitionTask = nil
}
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
}
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
Edit:
Here is additional code relating to the engine:
declaration in viewdidload
private let audioEngine = AVAudioEngine()
And attempt to start it later in startRecording method referenced above:
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("audioEngine couldn't start because of an error.")
}