GetWavHeader andGetWavData

Share your advanced PureBasic knowledge/code with the community.
Froggerprogger
Enthusiast
Enthusiast
Posts: 423
Joined: Fri Apr 25, 2003 5:22 pm
Contact:

GetWavHeader andGetWavData

Post by Froggerprogger »

Code: Select all

;- Get the Header and the Data of an WAV-File
;-
;- by Froggerprogger 05.04.04

#File_Temp = 0

Structure WAVEFORMATEX
  wFormatTag.w        ; compression Code (1 = WAV_FORMAT_PCM = uncompressed PCM)
  nChannels.w         ; number of channels (1 = mono, 2 = stereo, ...)
  nSamplesPerSec.l    ; samplerate (usually 11025, 22050, 32000, 44100, 48000 or 96000)
  nAvgBytesPerSec.l   ; average bytes per sec ( = samplerate * blockalign)
  nBlockAlign.w       ; number of bytes per sample slice = RoundUp(significantBitsPerSample / 8) * NumChannels 
  wBitsPerSample.w    ; bits per sample (normally 8, 16, 24 or 32)
  cbSize.w            ; length of extra-data in bytes
EndStructure

Structure WAVDATA
  mem.l  ; pointer to memory
  size.l  ; length of WAV data
EndStructure

Procedure.l GetWavHeader(*wavfmt.WAVEFORMATEX, filename.s)
  Protected fmtSize.l
  
  If OpenFile(#File_Temp, filename)
    ; check for the ASCII-String "RIFF" at start of file
    If ReadLong() <> 'FFIR' : ProcedureReturn #False : EndIf
    ; just ignore the following Long-value giving the length of the RIFF-chunk
    ReadLong() 
    ; check for the ASCII-String "WAVE" that identifies the RIFF-chunk as WAV-Format
    If ReadLong() <> 'EVAW' : ProcedureReturn #False : EndIf
    ; search for the format-chunk, normally it follows directly 
    While ReadLong() <> ' tmf' And Eof(#File_Temp) = #False
      FileSeek(Loc()-3) ; set back the filepointer by three to scan byte per byte
    Wend
    ; get the size of the fmt-chunk. normally 16 if it contains no extra-data
    fmtSize = ReadLong()
    *wavfmt\wFormatTag = ReadWord()
    *wavfmt\nChannels = ReadWord()
    *wavfmt\nSamplesPerSec = ReadLong()
    *wavfmt\nAvgBytesPerSec = ReadLong()
    *wavfmt\nBlockAlign = ReadWord()
    *wavfmt\wBitsPerSample = ReadWord()
    If fmtSize > 16
      *wavfmt\cbSize = ReadWord()
    Else
      *wavfmt\cbSize = 0
    EndIf

    CloseFile(#File_Temp)
    ProcedureReturn #True
  Else
    ProcedureReturn #False
  EndIf
EndProcedure

Procedure.l GetWAVData(*wavdata.WAVDATA, filename.s)
  If OpenFile(#File_Temp, filename)
    While ReadLong() <> 'atad' And Eof(#File_Temp) = #False
      FileSeek(Loc()-3) ; set back the filepointer by three to scan byte per byte
    Wend
    *wavdata\size = ReadLong()
    *wavdata\mem = AllocateMemory(*wavdata\size)
    ReadData(*wavdata\mem, *wavdata\size)

    CloseFile(#File_Temp)
    ProcedureReturn #True
  Else
    ProcedureReturn #False
  EndIf
EndProcedure
%1>>1+1*1/1-1!1|1&1<<$1=1