在swift中将浮点数组写入wav音频文件

我现在有这个流程:我使用AudioEngine录制音频,将其发送到音频处理库并获取音频缓冲区,然后我有强烈的意愿将其写入wav文件,但我完全混淆了如何做到这一点迅速。

我已尝试从另一个stackoverflow答案的这个片段,但它写了一个空的和损坏的文件。(将一个pcm加载到AVAudioPCMBuffer )

//get data from library var len : CLong = 0 let res: UnsafePointer = getData(CLong(), &len ) let bufferPointer: UnsafeBufferPointer = UnsafeBufferPointer(start: res, count: len) //tranform it to Data let arrayDouble = Array(bufferPointer) let arrayFloats = arrayDouble.map{Float($0)} let data = try Data(buffer: bufferPointer) //attempt to write in file do { let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 2, interleaved: false) var buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(data.count)) buffer.floatChannelData!.pointee.withMemoryRebound(to: UInt8.self, capacity: data.count) { let stream = OutputStream(toBuffer: $0, capacity: data.count) stream.open() _ = data.withUnsafeBytes { stream.write($0, maxLength: data.count) } stream.close() } //settings are from AudioEngine.inputNode!.inputFormat(forBus: 0).settings var audioFile = try AVAudioFile(forWriting: url, settings: settings) try audioFile.write(from: buffer) } catch let error as NSError { print("ERROR HERE", error.localizedDescription) } 

所以,我想我做的这个floatChannelData转换错误或一切都错了。 任何建议或指示在哪里阅读它将是伟大的!

有了很好的同事帮助,我们设法让它发挥作用。 显然,填充后的AudioPCMBuffer也需要通知它的新大小。 我也使用完全错误的格式。

这是代码:

 let SAMPLE_RATE = Float64(16000.0) let outputFormatSettings = [ AVFormatIDKey:kAudioFormatLinearPCM, AVLinearPCMBitDepthKey:32, AVLinearPCMIsFloatKey: true, // AVLinearPCMIsBigEndianKey: false, AVSampleRateKey: SAMPLE_RATE, AVNumberOfChannelsKey: 1 ] as [String : Any] let audioFile = try? AVAudioFile(forWriting: url, settings: outputFormatSettings, commonFormat: AVAudioCommonFormat.pcmFormatFloat32, interleaved: true) let bufferFormat = AVAudioFormat(settings: outputFormatSettings) let outputBuffer = AVAudioPCMBuffer(pcmFormat: bufferFormat, frameCapacity: AVAudioFrameCount(buff.count)) // i had my samples in doubles, so convert then write for i in 0..