FerasAS
FerasAS

Reputation: 293

How to use AVAudioNodeTapBlock in a tap in AVAudioEngine.

I am trying to install a tap on an AVAudioEngine. I have the current code:

    guard let engine = engine, let input = engine.inputNode else {
        print("error!")
        return
    }
    let format = input.inputFormat(forBus: 0)
    let bufferSize = 4096
    input.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: format, block: )

I am unsure on what goes in the block. There isn't much documentation on this. I have found this: https://developer.apple.com/reference/avfoundation/avaudionodetapblock?language=objc

Could someone explain how to use this?

Thanks,

Feras A.

Upvotes: 4

Views: 1464

Answers (1)

OOPer
OOPer

Reputation: 47886

You'd better check the Swift version of the reference, if you want to write it in Swift.

Declaration

typealias AVAudioNodeTapBlock = (AVAudioPCMBuffer, AVAudioTime) -> Void

You need to pass a closure taking two arguments and returning nothing, so you can write it as:

    input.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: format, block: {buffer, when in
        //...
    })

The type of two arguments buffer and when are AVAudioPCMBuffer and AVAudioTime respectively.

So, if you want to record the tapped audio into an audio file, you can write something like this:

    input.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: format, block: {buffer, when in
        do {
            try self.audioFile?.write(from: buffer)
        } catch {
            print(error)
        }
    })

(Assume audioFile is an instance property of type AVAudioFile?.)

Anyway, you need to know how to use AVAudioPCMBuffer.


I'm not sure if input.inputFormat(forBus: 0) can be an appropriate format in your case, but that may be another issue.

Upvotes: 2

Related Questions