Author: Kniebusch Horst
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?
Answer:
First you have to know what the structure of a wave file is. I'd create a record
which represent this structure:
1 type2 TWaveHeader = record3 ident1: array[0..3] of Char; // Must be "RIFF"4 len: DWORD; // Remaining length after this header5 ident2: array[0..3] of Char; // Must be "WAVE"6 ident3: array[0..3] of Char; // Must be "fmt "7 reserv: DWORD; // Reserved 4 bytes8 wFormatTag: Word; // format type9 nChannels: Word; // number of channels (i.e. mono, stereo, 10 etc.)
11 nSamplesPerSec: DWORD; //sample rate12 nAvgBytesPerSec: DWORD; //for buffer estimation13 nBlockAlign: Word; //block size of data14 wBitsPerSample: Word; //number of bits per sample of mono data15 cbSize: Word; //the count in bytes of the size of16 ident4: array[0..3] of Char; //Must be "data"17 end;
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:
18 function GetWaveHeader(FileName: TFilename): TWaveHeader;
19 const20 riff = 'RIFF';
21 wave = 'WAVE';
22 var23 f: TFileStream;
24 w: TWaveHeader;
25 begin26 ifnot FileExists(Filename) then27 exit; //exit the function if the file does not exists28 29 try30 f := TFileStream.create(Filename, fmOpenRead);
31 f.read(w, Sizeof(w)); //Reading the file header32 33 if w.ident1 <> riff then34 begin//Test if it is a RIFF file, otherwise exit35 Showmessage('This is not a RIFF File');
36 exit;
37 end;
38 39 if w.ident2 <> wave then40 begin//Test if it is a wave file, otherwise exit41 Showmessage('This is not a valid wave file');
42 exit;
43 end;
44 45 finally46 f.free;
47 end;
48 49 Result := w;
50 end;
I hope this example will help you to work with wave files in your application.