This tutorial explains how to play audio in an Android app made in Xamarin. The audio can be played when a screen loads or when an event occurs such as a button click or change in a variable’s value. For this tutorial, we will play a sound when a button is tapped.
Start by creating a new app solution in Xamarin (click File > New Solution). Select Android App as the project template. Click Next.
Give the new app a name. Then click Next.
Confirm the solution and project name, Make sure you specify a folder to store your project files in and then click Create.
Open the Main.axml file (in Resources > layout). Delete the button already there. Save the file.
Open the MainActivity.cs file and delete the highlighted lines of code (these lines for the button are not needed anymore as we won’t be using the default button).
Right-click on the Resources folder. Select Add > New Folder.
Give the new folder the name ‘raw’ and then press Enter.
Select the new ‘raw’ folder and right-click it. Then click Add > Add files from folder.
Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.
Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.
Then select Copy the file to the directory and click OK. This file will be copied to the project’s raw folder. You should then be able to see the audio file in the raw folder from the Solution panel.
Open the Main.axml file again and drag a Button element from the Toolbox onto the phone screen. Change the button’s Id value to @+id/playButton. Then change its Text value to Play Sound. Save this file.
Open the MainActivity.cs file again. Add the following highlighted line of code to the top section of the existing code. This will give us access to Android.Media.
Add the following two highlighted lines of code to the MainActivity.cs file to define the MediaPlayer element and to include the audio file in the code. Replace mysound with the name of your audio file (there is no need to include the .mp3 extension).
Now add the following two highlighted lines of code to define the Button element and access the playButton button from the screen.
Now add a click event for the button inside the OnCreate method. As you type playButton.Click+= and press the spacebar key you will see a list of options. You should see the option to create the PlayButton_Click method (if you don’t, start typing its name until it shows up – as shown below). Double-click this option from the list to create a new method.
Inside the new PlayButton_Click method add the line _player.Start(); – this will play the sound file when the button is clicked/tapped by the user. You can use this line anywhere in your app to play the sound (not just on a click event).
That’s it! Now go and test your app. Hint: You can also add a button that runs the line of code _player.Stop(); to stop the audio file playing.