Brandon Coetzee Brandon Coetzee - 2 months ago 6
Java Question

Soundpool, how to stop a sound thats playing?

I have read the other posts, but I still don't understand how to stop a sound that's playing, I want that when I press a button a sound will be played, and when I press another button I want the sound to stop playing, if anyone could help me that would be great.

Answer

You need to create a Stream ID and call the stop() method, like so:

SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);

static int StreamID;
static int Sound;

Sound = soundPool.load(this, R.raw.sndRes, 1);
...

btnStart.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        StreamID = soundPool.play(Sound, 1, 1, 0, 0, 1);
    }
});

and how to stop the sound :

btnStop.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        soundPool.stop(StreamID);
    }
});
Comments