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 변환된 데이터 처리
}
.... 생략 ....
'Swift > 문법' 카테고리의 다른 글
[SWIFT]UnsafeMutablePointer<AudioBufferList> to CMSampleBuffer 변경 (0) | 2023.06.26 |
---|---|
[SWIFT]AVAudioPCMBuffer to CMSampleBuffer 변경 (0) | 2023.06.26 |
[SWIFT]두 배열에서 중복되지 않는 항목 찾기 (0) | 2023.06.09 |
[SWIFT]두 배열에서 중복되는 항목 찾기 (0) | 2023.06.09 |
[SWIFT]map,reduce를 이용해서 Dictionary 배열의 전체 요소의 카운트 합계 계산 (0) | 2023.06.09 |