Created
December 31, 2020 02:28
-
-
Save johnny77221/3a89eed333586ebc9e94072592ebbbc0 to your computer and use it in GitHub Desktop.
Swift 5 version syntax correction for https://stackoverflow.com/a/63682544
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func extractSubchunks(data:Data) -> RiffFile? { | |
var data = data | |
var chunks = [SubChunk]() | |
let position = data.subdata(in: 8..<12) | |
let filelengthBytes = data.subdata(in: 4..<8).map { UInt32($0) } | |
let filelength: UInt32 = filelengthBytes[0] << 24 + filelengthBytes[1] << 16 + filelengthBytes[2] << 8 + filelengthBytes[3] | |
let wave = String(bytes: position, encoding: .utf8) ?? "NoName" | |
guard wave == "WAVE" else { | |
print("File is \(wave) not WAVE") | |
return nil | |
} | |
data.removeSubrange(0..<12) | |
print("Found chunks") | |
while data.count != 0{ | |
let position = data.subdata(in: 0..<4) | |
let lengthBytes = data.subdata(in: 4..<8).map { UInt32($0) } | |
let length: UInt32 = lengthBytes[0] << 24 + lengthBytes[1] << 16 + lengthBytes[2] << 8 + lengthBytes[3] | |
guard let current = String(bytes: position, encoding: .utf8) else{ | |
return nil | |
} | |
data.removeSubrange(0..<8) | |
let chunkData = data.subdata(in: 0..<Int(length)) | |
data.removeSubrange(0..<Int(length)) | |
let subchunk = SubChunk(name: current, size: Int(length), data: chunkData) | |
chunks.append(subchunk) | |
print(subchunk.debugDescription) | |
} | |
let riff = RiffFile(size: Int(filelength), subChunks: chunks) | |
return riff | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment