Search code examples
c#androidxamarinmediarecorderandroid-mediarecorder

Android.Media.MediaRecorder - delay when recording audio, with sections of silence


Please help solve the problem. To record an audio file, I use Android.Media.MediaRecorder. As a result, I get a section with silence 650 milliseconds at the beginning and at the end of the file. And it turns out that part of the phrase at the beginning and at the end is not recorded, only silence.

public static async Task Record(CancellationToken token)
    {
        try
        {
            var filename = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "/temp.amr";
            var tmp = new Java.IO.File(filename);
            if (tmp.Exists()) tmp.Delete();
            var recorder = new MediaRecorder();
            recorder.SetAudioSource(AudioSource.Mic);
            recorder.SetOutputFormat(OutputFormat.AmrNb);
            recorder.SetAudioEncoder(AudioEncoder.AmrNb);
            recorder.SetOutputFile(filename);
            recorder.Prepare();
            recorder.Start();
            try
            {
                var div = MAX_RECORD_TIME / 100;
                for(int i=0; i<div; i++)
                {
                    IncrementProgressBar(100 / div);
                    await Task.Delay(div, token);
                }
                fSave = true;
            }
            catch (OperationCanceledException) { }
            recorder.Stop();
        }
        catch (Exception e)
        {
            string s = context.GetText(Resource.String.err_unexpected) + "\r" + e.Message;
            handler.ToastMessage(s, ToastLength.Short);
        }
    }

Solution

  • This problem cannot be adressed through code, It seems like it is a hardware problem. You can see the same delay in the default Camera app, which also uses MediaRecorder. Unfortunately some device will behave differently.

    The Solution is to use the AudioRecorder class which is by far more flexible since it is closer to the hardware