Audio/Video Recording in Android Xamarin

This article describes about how to add features of Audio, Video recording, Playback and Audio Notifications to Android app using Xamarin.

Create a new Xamarin.Android project, select project Properties ->Android Manifest and check select the CAMERA, RECORD_AUDIO and WRITE_EXTERNAL_STORAGE

1) Record and Paly Audio:
a) This article explains Record an Audio with MediaRecorder class and Paly an Audio with Media Player class.
b) Add four buttons in Main.axml for Start/End Recording and Start/Stop Playing.

  <Button
            
android:id="@+id/startRecordingButton"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="Start Recording"
             
android:layout_below="@id/title"
             
android:layout_alignLeft="@id/title" />
        <Button
            
android:id="@+id/endRecordingButton"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="End Recording"
             
android:layout_below="@id/title"
             
android:layout_toRightOf="@id/startRecordingButton" />
<Button
            
android:id="@+id/startPlaybackButton"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="Start Playback "
             
android:layout_below="@id/startRecordingButton"
             
android:layout_alignLeft="@id/title" />
        <Button
            
android:id="@+id/endPlaybackButton"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="End Playback" />

c) In the Activity class add a variable for a MediaRecorder, MediaPlayer and also add variables for buttons, so that they can be enabled and disabled based on the start and Stop actions, when Start Recording started, all buttons will be disabled except End Recording.

MediaRecorder recorder = null;
        Button startRecording = null;
        Button stopRecording = null;
        Button startPlayback = null;
        Button stopPlayback = null;

d) Define the path where the audio file will be written.
static string filePath ="/sdcard/testAudio.mp4";

e) In the OnCreate method of Activity, find the references of buttons as below.

startRecording = FindViewById<Button>(Resource.Id.startRecordingButton);
stopRecording = FindViewById<Button>(Resource.Id.endRecordingButton);
startPlayback = FindViewById<Button>(Resource.Id.startPlaybackButton);
stopPlayback = FindViewById<Button>(Resource.Id.endPlaybackButton);

f) Create a method to Start Recording an Audio

public void StartRecorder ()
{
try {

if (File.Exists (filePath))
File.Delete (filePath);
if (recorder == null)
recorder = new MediaRecorder ();
                               else
recorder.Reset ();

recorder.SetAudioSource (AudioSource.Mic);
recorder.SetOutputFormat (OutputFormat.Mpeg4);
recorder.SetAudioEncoder (AudioEncoder.AmrNb);
recorder.SetOutputFile (filePath);
     recorder.Start ();
                     recorder.Prepare ();


} catch (Exception ex) {
Console.Out.WriteLine (ex.StackTrace);
}
}

g) Create a method to handle the button state, for example when start is clicked disables all the buttons except End button.

void handleButtonState()
        {
             startRecording.Enabled = false;
             stopRecording.Enabled = false;
             startPlayback.Enabled = false;
             stopPlayback.Enabled = false;
         if (isRecording)
            {
                stopRecording.Enabled = true;
                 return;
            }

            if (isPlaying)
            {
                stopPlayback.Enabled = true;
                 return;
            }
            else if (haveRecording)
            {
                startPlayback.Enabled = true;
            }

                startRecording.Enabled = true;
      }

h) Now, call above created methods on Start Record button click event.

        startRecording.Click += delegate
            {
                StartRecorder();
                disableAllButtons();
                isRecording = true;
                haveRecording = true;
                handleButtonState();
            };

i) On Stop Record button click stop and release the recorder to start again if required.

            stopRecording.Click += delegate
             {
           if (recorder != null) {
recorder.Stop ();
recorder.Release ();
recorder = null;
}        
                isRecording = false;
                handleButtonState();
            };

j) On Start Play button click event, start the media player and enable, disable the buttons as below.

startPlayback.Click += delegate
             {
try {
if (player == null) {
player = new MediaPlayer ();
} else {
player.Reset ();
}
Java.IO.File file = new Java.IO.File (filePath);
     Java.IO.FileInputStream fis = new Java.IO.FileInputStream (file);
player.SetDataSource(filePath);
player.Prepare ();
player.Start ();
}
                  catch (Exception ex) {
Console.Out.WriteLine (ex.StackTrace);
}                disableAllButtons();
                isPlaying = true;
                handleButtonState();
            };

K) On Stop playing button click, stop and release the player.
    
stopPlayback.Click += delegate
            {
               if (recorder != null) {
recorder.Stop ();
recorder.Release ();
recorder = null;
}                isPlaying = false;
                 handleButtonState();
             };

2) Record and Play Audio
Using classes such as VideoView and MediaRecorder, Android applications can add features as video recording and play back.
a) Add buttons to Main.axml to start, stop and paly the recoding. Also add a VideoView video preview while recoding and playing.

<Button
            
android:id="@+id/Record"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="Record" />
        <Button
            
android:id="@+id/Stop"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="Stop" />
        <Button
            
android:id="@+id/Play"
             
android:layout_width="120dp"
             
android:layout_height="wrap_content"
             
android:text="Play" />
<VideoView
        
android:id="@+id/SampleVideoView"
         
android:layout_width="fill_parent"
        
android:layout_height="fill_parent" />

b) In Activity, add a class variable for the MediaRecorder and Camera.

MediaRecorder recorder;

c) In the OnCreate method, add code to get references for buttons, VideoView and path to write the video file.

           string path = Android.OS.Environment.ExternalStorageDirectory.Name + "/test.mp4";

            var record = FindViewById<Button>(Resource.Id.Record);
            var stop = FindViewById<Button>(Resource.Id.Stop);
            var play = FindViewById<Button>(Resource.Id.Play);
            var video = FindViewById<VideoView>(Resource.Id.SampleVideoView);

d) In the click event handler for the record button, initialize the recorder, Camera and attach to MediaRecorder.

record.Click += delegate
             {
                  if (File.Exists(path))
                    File.Delete(path);
                video.StopPlayback();
                mCamera = Camera.Open();
                recorder = new MediaRecorder();
                 mCamera.Unlock();
                 recorder.SetCamera(mCamera);
                 recorder.SetVideoSource(VideoSource.Camera);
                  recorder.SetAudioSource(AudioSource.Mic);
                 recorder.SetOutputFormat(OutputFormat.Default);
                 recorder.SetVideoEncoder(VideoEncoder.Default);
                  recorder.SetAudioEncoder(AudioEncoder.Default);
                  recorder.SetMaxDuration(10000);
                 recorder.SetOutputFile(path);
                 recorder.SetPreviewDisplay(video.Holder.Surface);
                  recorder.Prepare();
                 recorder.Start();
            };

e) In the click event handler of the Stop button, stop the recorder, camera and release.

stop.Click += delegate
             {

                 if (recorder != null)
                 {
                     recorder.Stop();
                     recorder.Reset();
                      recorder.Release();
                    recorder = null;
                     mCamera.Lock();
                      if (mCamera != null)
                     {
                          mCamera.Release();        // release the camera for other applications
                        mCamera = null;
                    }


                }
            };

f) Finally, OnDestroy clean up the recorder.

protected override void OnDestroy()
        {
             base.OnDestroy();

             if (recorder != null)
            {
                 recorder.Release();
                recorder.Dispose();
                recorder = null;
            }
        }

3) Audio Notifications:

The best way to see audio notifications in action is to call the test phone, keep the call open for a while and then end the call while there is an ongoing operation. Audio-focus will be taken away and then granted again when the call is complete.

Refer the code sample for further reference.

Test this app in Android device for accurate results as emulators might not be configured with Media Recorder.

Download the sample from below link.
http://nullskull.com/FileUpload/-407123783_WorkingWithAudioAndVideo.zip      





By Siva Jagan Dhulipalla   Popularity  (2310 Views)