Skip to main content

Using Android SoundPool Build your Own Android Piano App

Playing any musical instrument on our Android device is the best thing that most of us like to do, be it Piano, Violin or Xylophone. Such apps basically use Android media library class known as Android SoundPool that handles short music tones on pressing of a button or object.

Android SoundPool

In this given below tutorial we will teach you how to build your own Piano using Android SoundPool class. For this we expect you have prior knowledge about ConstraintLayout in Android, if not please check out our tutorial on how to make your calculator app in Android.

Things Needed

  • Windows 7 or higher / Mac OS (Mavericks or higher) with minimum 4GB RAM
  • Android Studio (with SDK and latest API) and JAVA installed on system.
  • MP3 Piano Resource Files for each button. Link is here.

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 SoundPool class.
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

  1. activity_main.xml
  2. MainActivity.java
  3. AndroidManifest.xml (No permissions required)

Steps to Build Android Project

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

2. In activity_main.xml file, delete the ‘Hello World’ TextView and add 8 buttons. Each Button must have the height as 63sp and width as match_parent. These 8 buttons will have white (#FFFFFF) and grey (#E5E5E5) color as background. Add respective text i.e, C, D, E, F, G, A, B, and C. Text size should be 30sp and color as black (#000000) 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]’. The Code for Button C is as follows:


<Button
    android:id="@+id/c"
    android:layout_width="match_parent"
    android:layout_height="63dp"
    android:text="   C"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textAlignment="textStart"
    android:background="#ffffff"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:onClick="playC" />
 
3. 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 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:

<Button
    android:id="@+id/ds"
    android:layout_width="187dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="   D#"
    android:textAlignment="textStart"
    android:textSize="20sp"
    android:textStyle="bold"
    android:background="#000000"
    android:textColor="#ffffff"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/cs"
    android:onClick="playDS"/>
 
4. The complete XML Code for activity_main.xml is as follows:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.faultinmycode.mypiano.MainActivity">


    <Button
        android:id="@+id/c"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   C"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="playC" />

    <Button
        android:id="@+id/d"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   D"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#e5e5e5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/c"
        android:onClick="playD"/>

    <Button
        android:id="@+id/e"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   E"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/d"
        android:onClick="playE"/>

    <Button
        android:id="@+id/f"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   F"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#e5e5e5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/e"
        android:onClick="playF"/>

    <Button
        android:id="@+id/g"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:background="#ffffff"
        android:text="   G"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/f"
        android:onClick="playG"/>

    <Button
        android:id="@+id/a"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   A"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#e5e5e5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/g"
        android:onClick="playA"/>

    <Button
        android:id="@+id/b"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   B"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/a"
        android:onClick="playB"/>

    <Button
        android:id="@+id/cc"
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:text="   C"
        android:textSize="30sp"
        android:textStyle="bold"
        android:textAlignment="textStart"
        android:background="#e5e5e5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/b"
        android:onClick="playCC"/>

    <Button
        android:id="@+id/cs"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="40sp"
        android:text="   C#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="playCS"/>

    <Button
        android:id="@+id/ds"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="   D#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cs"
        android:onClick="playDS"/>

    <Button
        android:id="@+id/fs"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:text="   F#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ds"
        android:onClick="playFS"/>

    <Button
        android:id="@+id/gs"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="   G#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fs"
        android:onClick="playGS"/>

    <Button
        android:id="@+id/as"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="   A#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gs"
        android:onClick="playAS"/>

    <Button
        android:id="@+id/css"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:text="   C#"
        android:textAlignment="textStart"
        android:textSize="20sp"
        android:textStyle="bold"
        android:background="#000000"
        android:textColor="#ffffff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/as"
        android:onClick="playCSS"/>


</android.support.constraint.ConstraintLayout>
 
5. Now go to MainActivity.java and create 14 int variables for each sound, as shown in code below.

private int csound;
private int dsound;
private int esound;
private int fsound;
private int gsound;
private int asound;
private int bsound;
private int ccsound;
private int cssound;
private int csssound;
private int dssound;
private int gssound;
private int assound;
private int fssound;
 
6. Now lets talk about the key class in this project which is Android SoundPool. We will use 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 mediaplayer over here instead of SoundPool, but we won’t recommend it because of SoundPool’s ability to manage multiple audio streams. So it use SoundPool in our project we will first import and create its object. Code is as follows:

private SoundPool mSoundPool;
 
7. Now in Android SoundPool you can actually control the volume of left and right speaker, give Priority to a particular audio file, Loop an Audio File and tweak its play speed. So to we will control these attributes of SoundPool using different variables as coded below:

private float LEFT_VOL = 1.0f;
private float RIGHT_VOL = 1.0f;
private int PRIORITY = 1;
private int LOOP = 0;
private float RATE = 1.0f;
 
8. Now create the SoundPool constructor using code below:

mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);

<em>//SoundPool(int maxStreams, int streamType, int srcQuality)</em>
9. Now for each sound variable created above, load it to its respective sound. Code for this will be as follows:

csound = mSoundPool.load(getApplicationContext(),R.raw.c,1);
dsound = mSoundPool.load(getApplicationContext(),R.raw.d,1);
esound = mSoundPool.load(getApplicationContext(),R.raw.e,1);
fsound = mSoundPool.load(getApplicationContext(),R.raw.f,1);
gsound = mSoundPool.load(getApplicationContext(),R.raw.g,1);
asound = mSoundPool.load(getApplicationContext(),R.raw.a,1);
bsound = mSoundPool.load(getApplicationContext(),R.raw.b,1);
cssound = mSoundPool.load(getApplicationContext(),R.raw.c_hash,1);
csssound = mSoundPool.load(getApplicationContext(),R.raw.c_hash,1);
ccsound = mSoundPool.load(getApplicationContext(),R.raw.c2,1);
assound = mSoundPool.load(getApplicationContext(),R.raw.a_hash,1);
fssound = mSoundPool.load(getApplicationContext(),R.raw.f_hash,1);
gssound = mSoundPool.load(getApplicationContext(),R.raw.g_hash,1);
dssound = mSoundPool.load(getApplicationContext(),R.raw.d_hash,1);
 
10. 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:

public void playC(View v){
    mSoundPool.play(csound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
}

11. The code for MainActivity.java file is here:

MainActivity.java
package com.faultinmycode.mypiano;

import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private SoundPool mSoundPool;
    private int csound;
    private int dsound;
    private int esound;
    private int fsound;
    private int gsound;
    private int asound;
    private int bsound;
    private int ccsound;
    private int cssound;
    private int csssound;
    private int dssound;
    private int gssound;
    private int assound;
    private int fssound;

    private float LEFT_VOL = 1.0f;
    private float RIGHT_VOL = 1.0f;
    private int PRIORITY = 1;
    private int LOOP = 0;
    private float RATE = 1.0f;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
        csound = mSoundPool.load(getApplicationContext(),R.raw.c,1);
        dsound = mSoundPool.load(getApplicationContext(),R.raw.d,1);
        esound = mSoundPool.load(getApplicationContext(),R.raw.e,1);
        fsound = mSoundPool.load(getApplicationContext(),R.raw.f,1);
        gsound = mSoundPool.load(getApplicationContext(),R.raw.g,1);
        asound = mSoundPool.load(getApplicationContext(),R.raw.a,1);
        bsound = mSoundPool.load(getApplicationContext(),R.raw.b,1);
        cssound = mSoundPool.load(getApplicationContext(),R.raw.c_hash,1);
        csssound = mSoundPool.load(getApplicationContext(),R.raw.c_hash,1);
        ccsound = mSoundPool.load(getApplicationContext(),R.raw.c2,1);
        assound = mSoundPool.load(getApplicationContext(),R.raw.a_hash,1);
        fssound = mSoundPool.load(getApplicationContext(),R.raw.f_hash,1);
        gssound = mSoundPool.load(getApplicationContext(),R.raw.g_hash,1);
        dssound = mSoundPool.load(getApplicationContext(),R.raw.d_hash,1);

    }

    public void playC(View v){
        mSoundPool.play(csound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playD(View v){
        mSoundPool.play(dsound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playE(View v){
        mSoundPool.play(esound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playF(View v){
        mSoundPool.play(fsound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playG(View v){
        mSoundPool.play(gsound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playA(View v){
        mSoundPool.play(asound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playB(View v){
        mSoundPool.play(bsound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playCC(View v){
        mSoundPool.play(ccsound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playCS(View v){
        mSoundPool.play(cssound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playDS(View v){
        mSoundPool.play(dssound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playFS(View v){
        mSoundPool.play(fssound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playGS(View v){
        mSoundPool.play(gssound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playAS(View v){
        mSoundPool.play(assound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }

    public void playCSS(View v){
        mSoundPool.play(csssound,LEFT_VOL,RIGHT_VOL,PRIORITY,LOOP,RATE);
    }



}
 
12. Now Run your app in your mobile, Play and enjoy your instrument! Share your experience in the comment section below.

Download this Android Piano SoundPool project from link here.

Found this project interesting? Check out our some other awesome projects here: Roadway to Android Development Course.

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I've used bitcoin.pdf file, you can use any of your choices.
Software F…

Python Turtle Example: Flappy Bird Development in under 10 mins!

Python Turtle Example | Develop Flappy Bird Clone in 10 mins In the following tutorial, we have used following Python libraries:
1. random: To generate obstacles at random position. 2. turtle: To help provide directions to the player. 3. vector from freegames: To 2-dimensional vectors.
Before developing the game, here is a screenshot of what you'll be developing in 10 mins.
Steps to create Python Flappy Bird Game:
1. Open Pycharm and install 'freegames' package by going to Files > Settings > Project Interpreter. 2. Click on '+' sign on right and search for 'freegames' package. 3. Import packages in your project by writing following lines of code:
from random import * from turtle import * from freegames import vector 4. There are two variables required in the game, one for Bird object and another for an array of obstacles:
bird = vector(0, 0) balls = []
5. Create function for the player response on screen tap:
def tap(x, y): "Move bird up in res…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…