extension Data {
    init(buffer: AVAudioPCMBuffer, time: AVAudioTime) {
        let audioBuffer = buffer.audioBufferList.pointee.mBuffers
        self.init(bytes: audioBuffer.mData!, count: Int(audioBuffer.mDataByteSize))
    }

    func makePCMBuffer(format: AVAudioFormat) -> AVAudioPCMBuffer? {
        
        let streamDesc = format.streamDescription.pointee
        let frameCapacity = UInt32(count) / streamDesc.mBytesPerFrame
        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { return nil }

        buffer.frameLength = buffer.frameCapacity
        let audioBuffer = buffer.audioBufferList.pointee.mBuffers

        withUnsafeBytes { (bufferPointer) in
            guard let addr = bufferPointer.baseAddress else { return }
            audioBuffer.mData?.copyMemory(from: addr, byteCount: Int(audioBuffer.mDataByteSize))
        }

        return buffer
    }
}

 

[사용방법]

func bytesToAudioBuffer(_ buf: [Int16], withFormat fmt: UnsafeMutablePointer<AudioStreamBasicDescription>) -> AVAudioPCMBuffer {

	let data = buf.withUnsafeBufferPointer {Data(buffer: $0)}
    let format = AVAudioFormat(streamDescription: fmt)!
    let pcmbufferdata = data.makePCMBuffer(format: format)

    return pcmbufferdata!   
}

						.... 생략 ....
                        
var streamDesc = AudioStreamBasicDescription()
        
let bytesPerSample: UInt32 = UInt32(MemoryLayout<Int16>.size)  // 2
streamDesc.mFormatID = kAudioFormatLinearPCM
        
streamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked  //kLinearPCMFormatFlagIsPacked
        
streamDesc.mBytesPerPacket = bytesPerSample// 2
streamDesc.mFramesPerPacket = 1
streamDesc.mBytesPerFrame = bytesPerSample //2
streamDesc.mChannelsPerFrame = 1 // 1
streamDesc.mBitsPerChannel = 8 * bytesPerSample
streamDesc.mSampleRate = 48000 //44100

subscribe { [weak self] chunkBuffer in
	guard let `self` = self else { return }
    
    let pcmBuffer = self.bytesToAudioBuffer(chunkBuffer.samples, withFormat: &(streamDesc))
	//AVAudioPCMBuffer 변환된 데이터 처리
}
				.... 생략 ....

+ Recent posts