In this article, we will be building a project on Xylophone using Java and XML in android. Xylophone originally is an instrument played by striking a row of wooden bars. This application will be implementing a Xylophone-like instrument that is capable of producing sounds. We will create few Buttons in this app that will act as keys of the instrument when struck. This is going to be a single activity application. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Add Colors: We need to add colors in the value of the resources directory. We will be using these colors for our Buttons.
Add Key Notes: Save these audio notes in the app > res > raw directory
Note: Reference article: Resource Raw Folder in Android Studio
Step 3: Working with the activity_main.xml file
The XML codes are used to build the structure of the activity as well as its styling part. In this XML file, we will create a LinearLayout with vertical orientation. This will contain seven Buttons each with different onClick functions. The width of the button reduces as we go down to give it a look of a xylophone and also to symbolize that the smaller the button less is the note sound. Below is the code for the activity_main.xml file.
Step 4: Working with the MainActivity.java file
In the MainActivity we need to create a new SoundPool. A Soundpool uses MediaPlayer library services to load audio files. We will create a function for each key button with a different audio note. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.