About reducing size of AVAudioPCMBuffer

Hi, I'm trying to send audio data via UDP.

I am using Network.framework with networking, so to use send method in NWConnection sending data must be Data type or confirm to DataProtocol.

To satisfy those conditions, I have implemented a method to convert from AVAudioPCMBuffer type to Data type.

func makeDataFromPCMBuffer(buffer: AVAudioPCMBuffer, time: AVAudioTime) -> Data {

        let audioBuffer = buffer.audioBufferList.pointee.mBuffers

        let data: Data!

        data = .init(bytes: audioBuffer.mData!, count: Int(audioBuffer.mDataByteSize))

        return data
    }

Implementation above is referenced from this post

The problem is that the size of converted data is too big to fit in UDP datagram and error below occurs when I try to send data.

I have found out that initial size of buffer is too big to fit in maximumDatagramSize.

Below is code regarding to buffer.

        let tapNode: AVAudioNode = mixerNode
        let format = tapNode.outputFormat(forBus: 0)
        tapNode.installTap(onBus: 0, bufferSize: 4096, format: format, block: { (buffer, time) in
            // size of buffer: AVAudioPCMBuffer is 19200 already.
            let bufferData = self.makeDataFromPCMBuffer(buffer: buffer, time: time)

            sharedConnection?.sendRecordedBuffer(buffer: bufferData)

        })

I need to reduce size of AVAudioPCMBuffer to fit in UDP datagram, But I can't find right way to do it.

What would be best way to make data fit in datagram?

I thought of dividing data in half, but this is UDP so I'm not sure how to handle those datas when one data has lost.

So I'm trying to make AVAudioPCMBuffer fit in datagram.

Any help would be very appreciated!

About reducing size of AVAudioPCMBuffer
 
 
Q