Creating a Virtual Piano Application for Android

Choosing the appropriate Theme for our Virtual Piano App

The User Interface of our Virtual Piano will take the whole part of the screen, so we need to define a NoActionBar theme for our application in the styles.xml file :

Creating the Keys for the Piano

First, we are going to create the user interface for our Piano Application. So, we need to create a dedicated PianoView. A Piano has some keys. So, we create a Key object representing a piano’s key.

Creating a dedicated PianoView

Now, we can create our dedicated PianoView. It will override the View from the Android standard SDK. We will render 14 white keys and 10 black keys for our Piano. We will use two lists to store the white and black keys of the Piano. Finally, we define a property for the AudioSoundPlayer object we will use to play the sounds associated to each key.

Playing the music of our Piano

To play the music of our Piano, we need to create the AudioSoundPlayer object seen previously in this tutorial. Each sound will be played in a dedicated thread. So, we need a property to store the PlayThread objects. Besides, we will use a SparseArray to associate each index of the keys with a sound name. Finally, we define two constants for the volumes of the sounds we will play :

Sound files stored in the assets folder

Creating the PlayThread object

Like said previously, we are going to use a dedicated thread for each sound played. So, we create a PlayThread object for this aim. The sound will be played by using the AudioTrack object of the Android standard SDK.

Defining the User Interface of our Piano Application

The components of our Piano Application written, we can define the User Interface of our Piano. It will be quite simple : just a PianoView matching the parent layout :

Writing the Java code of the Piano Activity

Finally, we can just have a look to the Java code of the PianoActivity. Nothing to write, all is already good :

Our Virtual Piano in Action

Now, it is the best part of our tutorial since we are going to put our Virtual Piano in action. If you followed the tutorial correctly, you should have the following result on your smartphone or tablet :

Our Virtual Piano App in Action

To go further

To go further, you could implement a feature to record the sounds played by a user. Or, you can also implement a feature to let the users to play pre-recorded musics by coloring the keys to touch.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store