如何将音频样本保存在文本文件中 --> Swift

How can I safe audiosamples in a textfile --> Swift

问题是如何将音频文件的音频样本保存到文本文件中。我有一个特殊情况,我将样本存储在 UnsafeMutableRawBufferPointers 数组中,现在我想知道如何将它们放入文本文件中。在 C++ 中,我会在这里采用流运算符,但是我是 Swift 的新手,想知道如何执行此操作。

到目前为止我的代码如下所示:

let Data = Array(UnsafeMutableRawBufferPointer(start:buffer.mData, count: Int(buffer.mDataByteSize))

您已有创建 UnsafeMutableRawBufferPointer 的代码。使用它来创建数据,并将其写入磁盘:

let buffer = UnsafeRawBufferPointer(start:buffer.mData, count: Int(buffer.mDataByteSize)
let data = Data.withUnsafeBytes(buffer)

let fileURL = //the path to which you want to save

data.write(to: fileURL, options: []

..你的缓冲区.....

let yourBuffer = Array(UnsafeMutableRawBufferPointer(start:buffer.mData, count: Int(buffer.mDataByteSize))
let dd = Data.withUnsafeBytes(yourBuffer)
let fileName = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first!.appendingPathComponent("yourFile")
let result = try? dd.write(to: fileName)

这应该会在您的下载目录中创建文件“yourFile”

请告诉我。

我通过避免使用指针数组的特殊情况解决了这个问题。如果其他人想将音频样本写入文本文件,这就是我通过 AVAudioFile 解决问题的方式:

if FileManager.default.fileExists(atPath: getFileURL().path)
        {
            do{
                //Load Audio into Buffer and then write it down to a .txt
                let file = try AVAudioFile(forReading: getFileURL())
                let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: false)
                
                guard let buf = AVAudioPCMBuffer(pcmFormat: format!, frameCapacity: AVAudioFrameCount(file.length)) else{
                    throw NSError()
                }
                try file.read(into: buf)
                guard buf.floatChannelData != nil else{print("Channel Buffer was not able to be created")
                    throw NSError()}
                
                let arraySize = Int(buf.frameLength)
                print(arraySize, "Samples saved")
                let samples = Array(UnsafeBufferPointer(start:buf.floatChannelData![0],count:arraySize))
                //Array is going to be encoded and safe
                let encoded = try! JSONEncoder().encode(samples)
                try encoded.write(to: outputURL())
                print("Textfile created.\n")
             }catch {print(error)}
            
            
        }else {print("AudioFile is missing")}