[英]Convert audio into raw PCM data of type [Double]
我正在嘗試將錄制的音頻文件轉換為 [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
。 有人知道解決方法嗎? 謝謝。
但AVAudioFormat
確實知道.PCMFormatFloat64
:
let format = AVAudioFormat(commonFormat: .PCMFormatFloat64, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
也許您的意思是AVAudioPCMBuffer
沒有float64ChannelData
便利屬性?
沒關系,您可以使用AVAudioPCMBuffer
的超類, AVAudioBuffer
擁有您需要能夠獲得原始Double
/ Float64
樣本的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)
那個代碼可能不再工作了。
這是新的工作代碼。
斯威夫特 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)))
更新到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)")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.