package org.geeksforgeeks.demo;
import android.media.SoundPool;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Constants
private static final int SIM_SOUND = 8;
private static final float LEFT_VOLUME = 1.0f;
private static final float RIGHT_VOLUME = 1.0f;
private static final int LOOP = 0;
private static final int PRIORITY = 0;
private static final float NORMAL_PLAY_RATE = 1.0f;
// SoundPool instance
private SoundPool mSoundPool;
// Sound IDs
private int mCSoundId1, mDSoundId2, mESoundId3, mFSoundId4;
private int mGSoundId5, mASoundId6, mBSoundId7, mc2SoundId8;
// Buttons
private Button c, d, e, f, g, a, b, c2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize SoundPool
mSoundPool = new SoundPool.Builder()
.setMaxStreams(SIM_SOUND)
.build();
// Initialize buttons
c = findViewById(R.id.c_key);
d = findViewById(R.id.d_key);
e = findViewById(R.id.e_key);
f = findViewById(R.id.f_key);
g = findViewById(R.id.g_key);
a = findViewById(R.id.a_key);
b = findViewById(R.id.b_key);
c2 = findViewById(R.id.c2_key);
// Load sound files
mCSoundId1 = mSoundPool.load(this, R.raw.note1_c, 1);
mDSoundId2 = mSoundPool.load(this, R.raw.note2_d, 1);
mESoundId3 = mSoundPool.load(this, R.raw.note3_e, 1);
mFSoundId4 = mSoundPool.load(this, R.raw.note4_f, 1);
mGSoundId5 = mSoundPool.load(this, R.raw.note5_g, 1);
mASoundId6 = mSoundPool.load(this, R.raw.note6_a, 1);
mBSoundId7 = mSoundPool.load(this, R.raw.note7_b, 1);
mc2SoundId8 = mSoundPool.load(this, R.raw.note8_c2, 1);
// Set onClickListeners for buttons
c.setOnClickListener(v -> mSoundPool.play(mCSoundId1, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
d.setOnClickListener(v -> mSoundPool.play(mDSoundId2, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
e.setOnClickListener(v -> mSoundPool.play(mESoundId3, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
f.setOnClickListener(v -> mSoundPool.play(mFSoundId4, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
g.setOnClickListener(v -> mSoundPool.play(mGSoundId5, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
a.setOnClickListener(v -> mSoundPool.play(mASoundId6, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
b.setOnClickListener(v -> mSoundPool.play(mBSoundId7, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
c2.setOnClickListener(v -> mSoundPool.play(mc2SoundId8, LEFT_VOLUME, RIGHT_VOLUME, PRIORITY, LOOP, NORMAL_PLAY_RATE));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSoundPool != null) {
mSoundPool.release();
mSoundPool = null;
}
}
}