gpt4 book ai didi

swift - 使用 CMSampleBuffer 生成 Float32 数组(Float32 PCM 数据)

转载 作者:行者123 更新时间:2023-11-30 11:26:26 31 4
gpt4 key购买 nike

我从摄像头获得了音频回调,其数据格式为 CMSampleBuffer,但我无法将此数据转换为 PCM 数据。

我按照Apple copyPCMData提供的文档进行操作, UnsafeMutablePointer , AudioBufferList但最后我得到的只是 0.0

这是我的代码:

private let pcmBufferPointer = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: 1024)

init(....){
//...
let unsafeRawPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 0)
let audioBuffer = AudioBuffer(mNumberChannels: 1, mDataByteSize: 4, mData: unsafeRawPointer)
let audioBufferList = AudioBufferList(mNumberBuffers: 0, mBuffers: audioBuffer)
self.pcmBufferPointer.initialize(repeating: audioBufferList, count: 1024)
}


//CMSampleBuffer obtained from AVCaptureAudioDataOutputSampleBufferDelegate
private func audioFrom(sampleBuffer: CMSampleBuffer) -> Void {
let status = CMSampleBufferCopyPCMDataIntoAudioBufferList(sampleBuffer, 0, 1024, pcmBufferPointer)
if status == 0 {
Logger.log(key: "Audio Sample Buffer Status", message: "Buffer copied to pointer")
let dataValue = pcmBufferPointer[0].mBuffers.mData!.load(as: Float32.self) //Tried with Int, Int16, Int32, Int64 and Float too
Logger.log(key: "PCM Data Value", message: "Data value : \(dataValue)") //prints 0.0
}else{
Logger.log(key: "Audio Sample", message: "Buffer allocation failed with status \(status)")
}
}

最佳答案

终于成功了。

必须添加额外的步骤将 AudioBufferList 指针转换为 AudioList 指针

if status == 0 {
let inputDataPtr = UnsafeMutableAudioBufferListPointer(pcmBufferPointer)
let mBuffers : AudioBuffer = inputDataPtr[0]
if let bufferPointer = UnsafeMutableRawPointer(mBuffers.mData){
let dataPointer = bufferPointer.assumingMemoryBound(to: Int16.self)
let dataArray = Array(UnsafeBufferPointer.init(start: dataPointer, count: 1024))
pcmArray.append(contentsOf: dataArray)
}else{
Logger.log(key: "Audio Sample", message: "Failed to generate audio sample")
}
}else{
Logger.log(key: "Audio Sample", message: "Buffer allocation failed with status \(status)")
}

以上代码仅适用于单 channel PCM 数据。对于 2 channel 数据,请参阅以下 GIST - https://gist.github.com/hotpaw2/ba815fc23b5d642705f2b1dedfaf0107

关于swift - 使用 CMSampleBuffer 生成 Float32 数组(Float32 PCM 数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50694570/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com