WAV文件ChunkSize计算逻辑疑问:请求解析各数值来源
Let's break down those confusing magic numbers (4, 8) in the formula by mapping them directly to the structure of a WAV file's RIFF chunk.
First, here's the core structure of a standard WAV file's top-level RIFF chunk:
RIFF Chunk Structure: 1. ChunkID: 4 bytes (fixed as "RIFF") 2. ChunkSize: 4 bytes (the field you're trying to understand) 3. Format: 4 bytes (fixed as "WAVE") 4. SubChunk1 (Format Chunk): - SubChunk1ID: 4 bytes (e.g., "fmt ") - SubChunk1Size: 4 bytes (size of the format data, usually 16 for PCM) - SubChunk1Data: [SubChunk1Size] bytes (audio format details like sample rate, bit depth) 5. SubChunk2 (Data Chunk): - SubChunk2ID: 4 bytes (e.g., "data") - SubChunk2Size: 4 bytes (size of the raw audio data) - SubChunk2Data: [SubChunk2Size] bytes (the actual sound samples)
Now let's unpack the formula from the documentation:4 + (8 + SubChunk1Size) + (8 + SubChunk2Size)
- The first
4corresponds to the Format field ("WAVE") which takes up exactly 4 bytes immediately after the ChunkSize field. - Each
8in the subchunk terms comes from combining two mandatory 4-byte fields in every WAV subchunk:- 4 bytes for the subchunk's unique ID (like "fmt " for the format chunk or "data" for the audio data chunk)
- 4 bytes for the subchunk's size value (SubChunk1Size or SubChunk2Size)
Adding those two gives 4 + 4 = 8. We then addSubChunk1Size/SubChunk2Sizeto account for the actual data stored in each subchunk.
The simplified 36 + SubChunk2Size version is just a shortcut for standard PCM WAV files, where SubChunk1Size is always 16. Plugging that value into the full formula:4 + (8 + 16) + (8 + SubChunk2Size) = 4 + 24 + 8 + SubChunk2Size = 36 + SubChunk2Size
And to confirm with the other note from the docs: "This is the size of the entire file in bytes minus 8 bytes for the two fields not included in this count: ChunkID and ChunkSize" — this checks out because the total file size is calculated as:ChunkID(4) + ChunkSize(4) + [the rest of the file (which equals ChunkSize)]
Rearranging that gives ChunkSize = Total File Size - 8 (subtracting the 4+4 bytes of ChunkID and ChunkSize themselves, which aren't included in the ChunkSize value).
内容的提问来源于stack exchange,提问作者Belphegor

