In the previous post (Audio Recording using MediaRecorder using Xamarin in Visual Studio), we have seen how to record an audio. In this post we are going to see how to play audio using Xamarin. The Simplest way to play audio in android is using the inbuilt MediaPlayer class.
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/playAudio" /> </LinearLayout>
Now go to MainActivity.cs and do the following.
Create the Click event handler for the button (myButton) and use the MediaPlayer to play audio.
In order to play audio the following steps has to be done in the following order.
- Create and instantiate the MediaPlayer
- Set the Source for the player by passing the source as parameter for the SetDataSource method.
- Initialize the playback by calling the Prepare
- Call the Start method to start playing.
Here is a quick visual representation of the steps that you can give a quick look.
The MediaPlayer starts Playing the Audio, if the audio has to be paused, resumed or stop, we can use the following methods.
- To pause the Audio use the Pause
- To resume the Audio use the Start Which resumes form where the audio has been paused.
- To stop the Audio recording use the Stop
- 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 Play Audio. which plays the audio provided as Data Source.
I hope this post helps in playing the audio using Xamarin.