Audio Functionality In Xamain.Forms Android

This article explains how to play audio in Xamarin.Forms Android applications. The final output of the code is an XAML page with a button where when the button is clicked, an audio will be played.

Step 1

Select "New project" at the left side of Visual Studio. A pop up window listing out different projects will be opened. Select "Cross-Platform" at the left side and then, select Blank App (Xamarin.Forms Portable), as shown in the figure.



Rename the application as "AudioApp". Then, click "OK" so that a new project with the name "AudioApp" is created.

Step 2

Create a new folder with the name "Raw" under the "Resources" folder of the Android project, as shown in the screenshot below. Download an mp3 file from "mp3 download websites" and copy the audio file to "Raw" folder of Android project.

Step 3

Create an interface with the name "ISound.cs" in portable project and copy the following code in it.

  1. public interface ISound  
  2. {  
  3.    bool playBeepSound();  
  4. }  
Step 4

Create a class file with the name "SoundService" in Android project and implement the interface "ISound.cs" which is created in portable project. Now, copy the following code in the SoundService.cs.
  1. private MediaPlayer _mediaPlayer;  
  2. public bool playBeepSound()  
  3. {  
  4.     _mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.Beep);  
  5.     _mediaPlayer.Start();  
  6.     return true;  
  7. }  
And, add "[assembly: Dependency(typeof(SoundService))]" above the namespace. The final code is shown in the screenshot below.



Step 5

Once you are done with this, create a new Forms XAML page with the name "TestAudio" and copy the following code.
  1. <Grid>  
  2.     <Grid.RowDefinitions>  
  3.         <RowDefinition Height="3*" />  
  4.         <RowDefinition Height="4*" />  
  5.         <RowDefinition Height="3*" />  
  6.     </Grid.RowDefinitions>  
  7.     <Grid Grid.Row="1">  
  8.         <Button VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="30" WidthRequest="120" BackgroundColor="Gray" Text="Play Audio" Clicked="Button_Clicked"></Button>  
  9.     </Grid>  
  10. </Grid>  


Step 6

In the button clicked event, write the following code
  1. DependencyService.Get<ISound>().playBeepSound();  


Step 7

In the "App.xaml.cs", set the main page as new AudioApp.TestAudio(). So, when the button is clicked, a beep sound will be played.

 


Similar Articles