iosswiftwavriff

How to remove the riff headers from wav file in Swift?


I want to just have the data chunk of the .wav file and exclude all other chunks i.e the riff headers.

        let voiceData = try? Data(contentsOf: soundUrl).advanced(by: 44)

I did try this but for some reason, there is still some baggage left before the actual audio. could anyone please help me with this issue. if there an efficient way to read the .wav file and only include the data section?


Solution

  • First, are you certain this is actually a WAV file. WAV does typically have 44 bytes of header. Why do you believe there is "some baggage?" How are you determining that?

    You can of course parse the RIFF format directly. The easiest (sloppiest) approach is to scan down until you find the bytes "data" (0x64 61 74 61). The next 4 bytes will the the length (in little-endian format, which you can skip if you're just going to read to the end), followed by the actual data you want.

    Finding the data bytes is done with range(of:)

    let dataBytes = Data([0x64, 0x61, 0x74, 0x61])
    if let dataRange = riff.range(of: dataBytes) {
        let start = dataRange.endIndex + 4  // Skip over length bytes
        let samples = riff[start...] // read the rest of the bytes
        // use samples
    }