我试图将录制的音频文件转换为[Double]类型的原始PCM数据。我找到了一种方法来加载音频并将其转换为[Float32]类型的PCM数据,如下所示:
// load audio from path
let file = try! AVAudioFile(forReading: self.soundFileURL)
// declare format
let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
// initialize audiobuffer with the length of the audio file
let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length))
// write to file
try! file.readIntoBuffer(buf)
// copy to array
let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength)))
问题是,我需要数据为[Double],而AVAudioPCMBuffer()只知道.PCMFormatFloat32
。有人知道解决方法吗?
谢谢。
答案 0 :(得分:1)
但AVAudioFormat
知道.PCMFormatFloat64
:
let format = AVAudioFormat(commonFormat: .PCMFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
也许您的意思是AVAudioPCMBuffer
没有float64ChannelData
便利属性?
没关系,您可以使用AVAudioPCMBuffer
的超类,AVAudioBuffer
可以获得原始Double
/ Float64
样本所需的每一个:
let abl = buf.audioBufferList.memory
let doubles = UnsafePointer<Double>(abl.mBuffers.mData)
doubles[0] // etc...
完整:
let file = try! AVAudioFile(forReading: self.soundFileURL)
let format = AVAudioFormat(commonFormat: .PCMFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: UInt32(file.length))
try! file.readIntoBuffer(buf)
let abl = buf.audioBufferList.memory
let doubles = UnsafePointer<Float64>(abl.mBuffers.mData)
答案 1 :(得分:1)
那段代码可能不再有用了。
这是新的工作代码。
Swift 3.2
let file = try! AVAudioFile(forReading: soundFileURL)
let format = AVAudioFormat(commonFormat: .PCMFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false)
let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: AVAudioFrameCount(file.length))
try! file.readIntoBuffer(buf)
let abl = Array(UnsafeBufferPointer(start: buf.audioBufferList, count: Int(buf.audioBufferList.pointee.mNumberBuffers)))
let buffer = audioBufferList[0].mBuffers
let mDataList = Array(UnsafeMutableRawBufferPointer(start: buffer.mData, count: Int(buffer.mDataByteSize)))
答案 2 :(得分:1)
已更新为 Swift 5
do {
let file = try AVAudioFile(forReading: soundFileURL)
if let format = AVAudioFormat(commonFormat: .pcmFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false), let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length)){
try file.read(into: buf)
let abl = Array(UnsafeBufferPointer(start: buf.audioBufferList, count: Int(buf.audioBufferList.pointee.mNumberBuffers)))
let buffer = buf.audioBufferList[0].mBuffers
let mDataList = Array(UnsafeMutableRawBufferPointer(start: buffer.mData, count: Int(buffer.mDataByteSize)))
}
} catch{
print("Audio Error: \(error)")
}