Basic Wave (WAV) File Header

Back to Homepage
Onvyder.com

Login to Edit
Administrators only

There are some problems when you try to read a wave file in your C++ program without any third party libraries. First, you discover that Windows API doesn't provide too much tools to process those files. In fact we have the Win32 API Waveform Audio module that doesn't help when trying to read wave files into memory. There are also some structures (WAVEFORMAT etc.), all trying to describe format chunk from the wavefile header, but they are useless anyway. Second, the wavefile format wasn't standarized when it was being developed, ending up with variable file header and many extension chunks.

Reading miscellaneous formats of wavefiles requires a lot of programming work. Let's limit ourselves to a specific group of wave files. Wave files that carry PCM data, and are composed of exactly two subchunks: 'fmt ' and 'data'. Now we are able to define the following structure:


#define BASICWAVEHEADER_SIZE   44

#define BWH_LE_RIFF    0x46464952
#define BWH_LE_WAVE    0x45564157
#define BWH_LE_FMT     0x20746D66
#define BWH_LE_DATA    0x61746164

typedef struct BasicWaveHeader
{
    DWORD   dwRiffID;          /* 'RIFF' = 0x52494646 */
    DWORD   dwRiffSize;        /* = 8 */
    DWORD   dwRiffType;        /* 'WAVE' = 0x57415645 */

    DWORD   dwFormatID;        /* 'fmt ' = 0x666D7420 */
    DWORD   dwFormatSize;      /* = 16 */
    WORD    wFormatTag;        /* format type (i.e. WAVE_FORMAT_PCM)*/
    WORD    wChannels;         /* number of channels (i.e. mono, stereo...) */
    DWORD   dwSamplesPerSec;   /* sample rate */
    DWORD   dwAvgBytesPerSec;  /* for buffer estimation */
    WORD    wBlockAlign;       /* block size of data */
    WORD    wBitsPerSample;    /* 8, 16, 24 or 32 */

    DWORD   dwDataID;          /* 'data' = 0x64617461 */
    DWORD   dwDataSize;        /* bytes of plain wave data to read */
}BasicWaveHeader;

How to use this?
1. Read the first BASICWAVEHEADER_SIZE (44) bytes from a file
2. Cast those bytes into BasicWaveHeader structure
3. Check it:
    // check whether this file is a valid wave file with appropriate format
    if( (wh.dwRiffID   != BWH_LE_RIFF) ||
        (wh.dwRiffType != BWH_LE_WAVE) ||
        (wh.dwFormatID != BWH_LE_FMT ) ||
        (wh.dwDataID   != BWH_LE_DATA) )
    {
        //bad file format
    }
4. If everything is OK, read the data. That's all.

Last changed on: 28 Dec 2007

(c)2007 Onvyder.com | All rights reserved.