In the previous post of Getting Started with Cross Platform Development with Xamarin and Visual Studio series, we have seen how to create a simple List View. In this post we are going to see how to record audio using Xamarin. The Simplest way to record audio in android is using the inbuilt MediaRecorder
class.
In order to use MediaRecorder we need to set the Record_Audio permission in the Android manifest.
To do that, right click on the Project -> Properties and then select Android Manifest.
Got to Required Permissions and select Record_Audio and save the file.
Lets create the User interface for the App.
Add a button in the Main.axml file, assign an id (myButton) to the button, so that we can use it in the cs files.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/recordAudio" /> </LinearLayout>
Now go to MainActivity.cs and do the following.
Create the Click event handler for the button (myButton) and using the MediaRecorder to start recording.
In order to record audio the following steps has to be done in the following order.
- Create and instantiate the MediaRecorder object.
- Specify the audio device to be used to record the audio by passing the audio source as parameter to the SetAudioSource method.
- Set the file format for the audio output by passing the file format as parameter to the SetOutputFormat.
- Set audio encoding type by passing the type as parameter to the SetAudioEncoder method.
- Set the output file to which the recorded audio gets stored by passing the file as parameter to the SetOutputFile method
- Initialize the recorder by calling the Prepare method.
- Call the Start method to start recording.
The MediaRecorder starts recording the Audio, if the recording has to be paused or stopped, we can use the following methods.
- To stop the Audio recording use the Stop method.
- To pause the Audio recording use the Pause method.
- Release method can use to release the resources when not needed.
Sample code is provided below.
when we run the app, we can see the button Start Recording to start the recording and Stop Recording to stop it.
That’s the audio is recorded and saved in the local storage under the name Audio_Recorded.3gp.
In our next blog we will see how to play back the audio.
I hope this post helps in recording the audio using Xamarin.
Pingback: Dew Drop – July 8, 2015 (#2049) | Morning Dew
Pingback: How to Play Audio using MediaPlayer using Xamarin in Visual Studio
Pingback: .NET Tips and Tricks from Daily .NET Tips – ( Visual Studio 2015, Windows Universal App Development, Microsoft Band, Xamarin ) – July 2015 Links | Abhijit's World of .NET