ios - 将音频转换为 [Double] 类型的原始 PCM 数据

标签 ios swift audio avfoundation avaudiofile

我正在尝试将录制的音频文件转换为 [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 的父类(super class),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)

关于ios - 将音频转换为 [Double] 类型的原始 PCM 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39210970/

相关文章:

ios - 禁用iOS键盘中的Enter按钮

ios - 我可以将自定义转场用于非视觉目的吗?

ios - 仅在 Apple Watch 上请求位置,无需配对手机上的代码

ios - 快速减去时间

ios - 使用 CIDetectorTypeFace 进行人脸识别时出错

c# - NAudio-初学者问题-在20ms音频文件缓冲区上运行

audio - 如何在jupyter笔记本上将音频数据转换为傅立叶?

iphone - AVMutableVideoComposition 以纵向模式捕获的旋转视频

audio - 有没有一种方法可以创建一个自定义UIButton来在按下事件时播放声音?

iOS segue.destinationViewController 不发送信息