Thursday, 3 October 2013

Reading Wave files (.wav) using C#


       One of my friend who is working on his project asked me this question,  So I decided to make a post which would be helpful to many amateurs.

       Wave file format is a subset of RIFF(Resource Interchange File Format) specification in which data are stored in "chunks".  To learn move about how .wav format works,  wiki would help.

       Since wave file is subset of RIFF,  they consist of two sub-chunks namely "fmt" and "data".  The "fmt" are headers which provide information about the file.  Then begins the "data" part.




        Since wave file is in bit stream format,  we use "BinaryReader" class to read the file.  Include the "System.IO" namespace.

       

     BinaryReader reader = new BinaryReader(new FileStream(@"zulu.wav",FileMode.Open));

       

        We use "byte[]" to store the data.
     
       

     byte[] sound;
      
 
       
         Then read the headers from the file.
     
       
  
     int chunkID = reader.ReadInt32();      
     int fileSize = reader.ReadInt32();     
     int riffType = reader.ReadInt32();     
     int fmtID = reader.ReadInt32();        
     int fmtSize = reader.ReadInt32();      
     int fmtCode = reader.ReadInt16();      
     int channels = reader.ReadInt16();     
     int sampleRate = reader.ReadInt32();   
     int fmtAvgBPS = reader.ReadInt32();    
     int fmtBlockAlign = reader.ReadInt16();
     int bitDepth = reader.ReadInt16();
  
 

        To read all the extra information present in the file,  we use following code.

       
    
     if(fmtSize == 18)                          
     {                                          
          // Read any extra values               
          int fmtExtraSize = reader.ReadInt16(); 
          reader.ReadBytes(fmtExtraSize);        
     }    
       
 

        The "fmt" part is done.  Now read the "data" part.

       
   
     int dataID = reader.ReadInt32();    
     int dataSize = reader.ReadInt32();  
     sound = reader.ReadBytes(dataSize);  
       
 

        The "sound" array contains the data of the .wav file.  You can now perform any operation you like to do with the file.  For example,  I just wanted to visualize the .wav file.  I used following code to do so.


       
     int i=1;
     int j=400-Convert.ToInt32(sound[0]);
     gra.DrawLine(a, 0, 400, i, j);
     Point prev=new Point(i,j);
     i++;
     Point next = new Point();
     foreach (byte temp in sound)
     {
          j=400-Convert.ToInt32(temp));
          next.X = i++;
          next.Y = j;
          gra.DrawLine(a, prev, next);
          prev = next;
     }
       
 


         The Output of the above code is shown below.




            Your Suggestions,  Opinions are most welcome.  Please do comment.


2 comments: