Can't attach AVAudioNode to AVAudioEngine

Viewed 29

I'm beginner at iOS development and going to record specific sound received from iPhone microphone. There's a requirment that the sound should be recorded only when snoring sound is detected. So I decided to use AVAudioEngine instead of AVAudioRecorder.

My idea is to use 2 AVAudioNodes that one is for detecting snoring sound and turning on Bool flag and the other is for writing(recording) audio data to local file.

But I'm in trouble at the very first.

Attaching a basic AVAudioNode to AVAudioEngine throws error that I can't understand:

'required condition is false: node != nil'

Why is the AVAudioNode nil?

2022-09-12 16:02:31.178318+0900 StatusBarTest[2464:140681] [avae]            AVAEInternal.h:76    required condition is false: [AVAudioEngine.mm:418:AttachNode: (node != nil)]
2022-09-12 16:02:31.178785+0900 StatusBarTest[2464:140681] *** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: node != nil'
*** First throw call stack:
(0x19d83c288 0x1b656c744 0x19d913488 ...)

libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
*** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: node != nil'
terminating with uncaught exception of type NSException

Belows are my Swift codes:

class Recorder {
    private let engine: AVAudioEngine
    private let audioNode: AVAudioNode

    init() {
        let session = AVAudioSession.sharedInstance()

        do {
            try session.setCategory(.record)
            try session.setActive(true, options: .notifyOthersOnDeactivation)
        } catch {
            print(error.localizedDescription)
        }

        self.engine = AVAudioEngine()
        self.audioNode = AVAudioNode()
        
        let inputNode = engine.inputNode
        let inputFormat = inputNode.outputFormat(forBus: 0)

        inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { (buffer, _) in
            print(buffer)
        }

        engine.attach(audioNode)  // <-- throws exception
        engine.prepare()

        try? engine.start()
    }
}
0 Answers
Related