Search code examples
androidaudio-recording

Android AudioRecord pcm16bit WAV files - can't be played externally?


I created a WAV file based from https://developer.xamarin.com/samples/monodroid/Example_WorkingWithAudio/ where the relevant code are as follows:

    private const int RECORDER_SAMPLERATE = 16000;
    private const ChannelIn RECORDER_CHANNELS = ChannelIn.Mono;
    private const Android.Media.Encoding RECORDER_AUDIO_ENCODING = Android.Media.Encoding.Pcm16bit;

   ...

    var bufferSize = AudioRecord.GetMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);

    audioBuffer = new byte[bufferSize];
    audioRecord = new AudioRecord(
        // Hardware source of recording.
        AudioSource.Mic,
        // Frequency
        RECORDER_SAMPLERATE,
        // Mono or stereo
        RECORDER_CHANNELS,
        // Audio encoding
        RECORDER_AUDIO_ENCODING,
        // Length of the audio clip.
        audioBuffer.Length
    );

    audioRecord.StartRecording();

    ...

    using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        {
            while (true)
            {
                if (endRecording)
                {
                    endRecording = false;
                    break;
                }
                try
                {
                    // Keep reading the buffer while there is audio input.
                    int numBytes = await audioRecord.ReadAsync(audioBuffer, 0, audioBuffer.Length);
                    await fileStream.WriteAsync(audioBuffer, 0, numBytes);
                    // Do something with the audio input.
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.Message);
                    break;
                }
            }
            fileStream.Close();
        }
        audioRecord.Stop();
        audioRecord.Release();

My question is - how can I play this .WAV file after copying in Windows (or other OS)? Here are my observations:

  • .WAV file can be played using Android's AudioTrack class, as shown in the https://developer.xamarin.com/samples/monodroid/Example_WorkingWithAudio/ code sample.
  • The code sample will create a testAudio.wav file in the /data/Example_WorkingWithAudio/files/ directory.
  • Try to copy this file to your Windows PC, then try playing the .WAV file with an audio player which supports .WAV. See that it won't be able to play the file.

Solution

  • to revert back, I found out that the created track needs to be converted to .WAV first. Here are 2 posts which helped me do it.

    http://www.edumobile.org/android/audio-recording-in-wav-format-in-android-programming/

    Recorded audio Using AndroidRecord API fails to play