Writing WAVE PCM header in Xamarin.Android

When recording (low level) PCM encoded audio in Android with AudioRecord, the application must continuously read the audio buffer and write the raw data to an audio file. One of downsides to using AudioRecord is that only raw uncompressed data is returned, meaning it’s missing the header which can only be created once the recording has completed. The application must create a WAVE header in order to play/stream outside of Android. AudioTrack will play the file just fine without a header but any another player won’t know what to do with it.

Creating header:

Image for post
Image for post
Image From: http://soundfile.sapp.org/doc/WaveFormat/

To create the header we first need to know what it needs to contain and exactly where. The diagram above displays the fields needed in the 44 bytes long header. I created a simple method WriteWavHeader(string filePath, int sampleRate, short bitsPerSample, short channels) to write the header, just supply the path to the audio file, sample rate, bitsPerSample and # of channels. The method takes care of opening the file, seeks to the beginning and writes the 44 bytes to complete our WAV file. The method uses BitConverter to write the bytes array to the header taking care of endianness.

There are benefits to recording with MediaRecorder as it’s done at a higher level, output is compressed, no need to write headers etc. however, you can’t start from an existing file and might cover that in future post.

Wanted to share this quick post on writing headers from Xamarin.Android and hope it helps someone trying to do the same. Happy Coding!

Written by

Principal Software Engineer at Command Health https://github.com/dannycabrera

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store