For the past few months I have been trying to build a basic piano keyboard for Android. In doing this, I have discovered that the information out there is quite scarce, so I had to do quite a bit of experimenting to get it working properly.
The best source I could find was this, and my work is, visually at least, almost identical, however I wanted to improve on it and, hopefully, I did just that.
Below you can see the code for the KeyboardView.java file. This houses the KeyboardView class which extends the View class and overrides some of its built-in methods:
onSizeChanged – depending of the size, here we define the keys themselves. Each key has a few parameters, such as it’s text, the sound it should play when pressed, and how it should be drown on the canvas. All this parameters are set in this method.
onDraw – this is where we actually draw the keyboard.
onTouchEvent – here we determine which keys are pressed, which are released, and we command the Sound_Pool accordingly. This was a tricky method to get right because of how Android handles multiple input.
Another class is KeyboardViewSmall which is basically the same as KeyboardView with the noticeable differences in onDraw and onTouchEvent.
For playing the sounds, I used a SoundPool object. I pre-load all the sounds (88 of them) in order to keep delay to a minimum. I have tried other ways to play the sounds, but I have found this to be the most versatile. The main difficulty with SoundPool is that there is no stopping a track once it’s started, but I worked around this by setting it’s volume down to 0, once the key is released (with a 500ms fade-out period).
This are the important bits of the application. Feel free to go through the code, and even compile it yourself and see how it works for you.
If there are any questions, feel free to ask, as I am aware that this article does not go into too much detail. Also, if you have any suggestions for improvements, leave a comment down below.