Working with WAV sound files in C#

I have been doing a lot of work recently on the Windows Mobile platform, and have had to work with integration of sounds within applications. The basic 'PlaySound' function has it's limitations and it is difficult to get smooth instantaneous playback.

As an alternative I have been making use of the Wave Api which has been part of Windows (desktop and mobile for many versions), however, it's interface is purely though the native APIs. This means for a C# developer -like me - you have to use Interop, and get to grips with the use of Native data structure using pointer and suchlike.

The first problem with this is understanding the various formats for WAV files and how to represent them with the native WAVE_FORMAT structure and it's variants.


The native structure (C++) for WAVEFORMATEX basically looks like this:

typedef struct {
  WORD wFormatTag; 
  WORD nChannels; 
  DWORD nSamplesPerSec; 
  DWORD nAvgBytesPerSec; 
  WORD nBlockAlign; 
  WORD wBitsPerSample; 
  WORD cbSize;

The structure is not that copmlex, but the information it contains needs to match the values stored within the header of the wave file that you want to play. In an application where you have total control of the format of the sound files, you can choose one format and hard code these values, however, you need to know the values up front. If you need to work with arbitrary wave files you need to be able to determine the parameters from the file itself.

Retrieving information from the header of the WAV file

There is an excellent reference to the structure and variation of WAVE files hosted by McGill University. Using this it is possible to build an application/library/class which can inspect a wave file and return the values for the WAVEFORMATEX structure.

You can download a console application which will retrieve information from an arbitrary wave file. I wrote this to help with the development and debugging of a wave audio class library for use with Windows Mobile applications.

Accessing the native wave audio API calls

To be continued!

Valid XHTML 1.0! | Valid CSS! | WCAG Approved AA
Page design by: John P Scott - Hosting with: Netcetera