What we will build

So the app we will build in this tutorial will have around 14 buttons, each having assigned to an onClick() method that’ll play the audio using the Android SoundPool class.

Android SoundPool

The buttons and their location will be set using ConstraintLayout introduced in API 9. 8 buttons will be white in color with C, D, E, F, G, A and B sound and 5 black color buttons with C#, D#, F#, G#, A#, and another C# sound.

Files Created in Process

activity_main.xml

MainActivity.java

AndroidManifest.xml (No permissions required)

Steps to Build Android Project

Open Android Studio and Create a new Project with app name as ‘My Piano’, Select to create an empty activity with MainAvticity.java class.

Now add 6 more buttons in this layout with very first C# button in between C and D white colored buttons.

You can constrain the next button i.e, D# below C# and to the end of the parent. Each button has a width of 187sp and height as wrap_content.

The text for each button is C#, D#, F#, G#, A# and C# again. These 6 buttons will have black (#000000) color as background with Text size should be 20sp and color as white (#FFFFFF) with bold style and alignment set to ‘textstart’.

Assign an onClick method to each button in the end, the method name we kept is ‘play[BUTTON_NAME]S’. The Code for Button D# is as follows:

Now let‘s talk about the key class in this project which is Android SoundPool.

We will use the Android SoundPool in our project because firstly, SoundPool can play audio files for applications and secondly it can also manage the number of audio streams being rendered at once, which is our case will be many keys pressed at once.

Though you may think about using the Android Mediaplayer over here instead of SoundPool, but we won’t recommend using it because of SoundPool’s ability to manage multiple audio streams. So to use Android SoundPool in our project we will first import and create its object. Code is as follows:

private SoundPool mSoundPool;

Now in Android SoundPool you can actually control the volume of the left and the right speaker, give Priority to a particular audio file, Loop an Audio File and tweak its play speed.

So we will control these attributes of SoundPool using different variables as coded below:

Voila, now all you need to do is to create an onClick public method for each button as set in activity_main.xml file above using play method in SoundPool class as shown in the code below for C button only: