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.
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!