2009. október 18., vasárnap

How to read the file header of a wave file


I want to open a wave file in my application, but how do I know that it is really a wave file and not just a file with *.wav extension?


First you have to know what the structure of a wave file is. I'd create a record which represent this structure:

  TWaveHeader = record
    ident1: array[0..3] of Char;      // Must be "RIFF"
    len: DWORD;                       // Remaining length after this header
    ident2: array[0..3] of Char;      // Must be "WAVE"
    ident3: array[0..3] of Char;      // Must be "fmt "
    reserv: DWORD;                    // Reserved 4 bytes
    wFormatTag: Word;                 // format type
    nChannels: Word;                  // number of channels (i.e. mono, stereo, etc.)
    nSamplesPerSec: DWORD;            //sample rate
    nAvgBytesPerSec: DWORD;           //for buffer estimation
    nBlockAlign: Word;                //block size of data
    wBitsPerSample: Word;             //number of bits per sample of mono data
    cbSize: Word;                     //the count in bytes of the size of
    ident4: array[0..3] of Char;      //Must be "data"

With this structure you can get all the information's about a wave file you want to.
After this header following the wave data which contains the data for playing the wave file.

Now we trying to get the information's from a wave file. To be sure it's really a wave file, we test the information's:

function GetWaveHeader(FileName: TFilename): TWaveHeader;
  riff = 'RIFF';
  wave = 'WAVE';
  f: TFileStream;
  w: TWaveHeader;
  if not FileExists(Filename) then
    exit; //exit the function if the file does not exists

    f := TFileStream.create(Filename, fmOpenRead);
    f.Read(w, Sizeof(w)); //Reading the file header

    if w.ident1 <> riff then
    begin //Test if it is a RIFF file, otherwise exit
      Showmessage('This is not a RIFF File');

    if w.ident2 <> wave then
    begin //Test if it is a wave file, otherwise exit
      Showmessage('This is not a valid wave file');


  Result := w;

I hope this example will help you to work with wave files in your application.

Nincsenek megjegyzések:

Megjegyzés küldése