How to convert PCM to G711 µlaw raw format

182 views Asked by At

I am trying PCM (microphone input)->G711 and am having trouble getting it to work.

With the current implementation, the conversion itself succeeds, but it is as if there is no data stored in the buffer.

I have been doing a lot of research, but I can't seem to find the cause of the problem, so I would appreciate your advice.


var audioEngine = AVAudioEngine()

var convertFormatBasicDescription = AudioStreamBasicDescription(
    mSampleRate: 8000,
    mFormatID: kAudioFormatULaw,
    mFormatFlags: AudioFormatFlags(kAudioFormatULaw),
    mBytesPerPacket: 1,
    mFramesPerPacket: 1,
    mBytesPerFrame: 1,
    mChannelsPerFrame: 1,
    mBitsPerChannel: 8,
    mReserved: 0
)

func convert () {
    let inputNode = audioEngine.inputNode
    let micInputFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: true)!    
    let convertFormat = AVAudioFormat(streamDescription: &convertFormatBasicDescription)!
    let converter = AVAudioConverter(from: micInputFormat, to: convertFormat)!
    
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: micInputFormat) { [weak self] (buffer, time) in
        
        var newBufferAvailable = true

        let inputCallback: AVAudioConverterInputBlock = { inNumPackets, outStatus in
            if newBufferAvailable {
                outStatus.pointee = .haveData
                newBufferAvailable = false
                return buffer
            } else {
                outStatus.pointee = .noDataNow
                return nil
            }
        }

        let convertedBuffer = AVAudioPCMBuffer(pcmFormat: convertFormat, frameCapacity: AVAudioFrameCount(convertFormat.sampleRate) * buffer.frameLength / AVAudioFrameCount(buffer.format.sampleRate))!
        convertedBuffer.frameLength = convertedBuffer.frameCapacity
        
        var error: NSError?
        let status = converter.convert(to: convertedBuffer, error: &error, withInputFrom: inputCallback)

        print(convertedBuffer.floatChannelData) <- nil
    }

    audioEngine.prepare()
    try audioEngine.start()
}

Thank you.

1

There are 1 answers

0
zones On

It was audioBufferList.pointee.mBuffers.mData, not floatChannelData, that was needed to get the data converted to G711.