-1

I have a activity that i'm using 12 button with different sound at them. Buttons should be play at the same time if user click both of them at once.

When i use MediaPlayer i couldn't manage to do this , then i learned about SoundPool and everything was fine.But with 12 different sounds I had to write so many row and i don't think that's the right way to do this.

Is this the right way to do this , when i write this for 12 sound it became to long ?

SoundPool sp1,sp2,sp3;
int id1,id2,id3;

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

sp1 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);
        sp2 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);
        sp3 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);

id1 = sp1.load(this,R.raw.p1,1);
        id2 = sp2.load(this,R.raw.p2,1);
        id3 = sp3.load(this,R.raw.p3,1);

}

public void p1Click(View v)
        {
            sp1.play(id1,1,1,1,0,1);
        }

public void p2Click(View v)
        {
            sp2.play(id1,1,1,1,0,1);
        }

public void p3Click(View v)
        {
            sp3.play(id1,1,1,1,0,1);
        }
Nick Friskel
  • 2,369
  • 2
  • 20
  • 33

1 Answers1

0

You only need one SoundPool (sp1):

sp1 = new SoundPool(12, AudioManager.STREAM_MUSIC,1);
id1 = sp1.load(this,R.raw.p1,1);
id2 = sp1.load(this,R.raw.p2,1);
...
sp1.play(id1,1,1,1,0,1);
sp1.play(id2,1,1,1,0,1);
...

(1) Note the 12 means you can play 12 sounds concurrently.
(2) Note keep track of your active sounds, it will be useful later. (sp1.play returns an integer):

int streamID = sp1.play(id1,1,1,1,0,1);
Jon Goodwin
  • 9,053
  • 5
  • 35
  • 54