简体   繁体   中英

How to save a Float array in Swift as txt file

First of all: I really want to save the array as .txt file. .plist is out of the question.

The reason: Afterwards I want to save it to a vector using C++. Realizing this with a wrapper already drove me crazy.

Here is my code:

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 konnte nicht erstellt werden")
                throw NSError()}

let samples = Array(UnsafeBufferPointer(start:buf.floatChannelData![0],count:Int(buf.frameLength)))
var wData = Data(samples)
try! wData.write(to: outputURL())
 

But it is not possible to initialize Data with Float values, or is it?

How can I write an Array of float Values into a .txt file?

The answer to the question itself (save it as txt), you can save your array of floats as a JSON string. It should be pretty straight forward to encode and decode it using JSONEncoder/JSONDecoder.

let values: [Float] = [-.pi, .zero, .pi, 1.5, 2.5]

let encoded = try! JSONEncoder().encode(values)
print(String(data: encoded, encoding: .utf8)!)  // "[-3.1415925025939941,0,3.1415925025939941,1.5,2.5]\n"
let decoded = try! JSONDecoder().decode([Float].self, from: encoded)  // [-3.141593, 0, 3.141593, 1.5, 2.5]

"But it is not possible to initialize Data with Float values, or is it?"

Yes it if definitely possible to convert an Array of Float to Data/Bytes and read it back. It is also preferred to preserve the exact values avoiding the conversion to string:

extension Array {
    var bytes: [UInt8] { withUnsafeBytes { .init($0) } }
    var data: Data { withUnsafeBytes { .init($0) } }
}
extension ContiguousBytes {
    func object<T>() -> T { withUnsafeBytes { $0.load(as: T.self) } }
    func objects<T>() -> [T] { withUnsafeBytes { .init($0.bindMemory(to: T.self)) } }
}

let values: [Float] = [-.pi, .zero, .pi, 1.5, 2.5]
let bytes = values.bytes  // [218, 15, 73, 192, 0, 0, 0, 0, 218, 15, 73, 64, 0, 0, 192, 63, 0, 0, 32, 64]
let data = values.data    // 20 bytes
let minusPI: Float = data.subdata(in: 0..<4).object() // -3.141593
let loaded1: [Float] = bytes.objects()  // [-3.141593, 0, 3.141593, 1.5, 2.5]
let loaded2: [Float] = data.objects()   // [-3.141593, 0, 3.141593, 1.5, 2.5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM