How to make an audio stop when another audio starts (bulk alot of audios)

51 Views Asked by At

I have 30-31 buttons and i want one to play at a time so if i click on a button it will play then when i click on the other button that one stops no matter which one it is it will stop this is the sample of the code its basically like this all through and repeats but just the numbers change hence 1,2,3,4 etc etc. :

    public void Button1Text(View view) {
        Media1 = MediaPlayer.create(QuranJ30MA.this, R.raw.hannaba);
        Media1.start();
    }

    public void Button1Text2(View view) {
        Button1p = MediaPlayer.create(QuranJ30MA.this, R.raw.mannaba);
        Button1p.start();
    }

I did try to look at others which wanted to do the same but since i am not very good with java I couldnt understand how to apply it on mine please also explain how it works if its not too much to ask i just want to learn thank you :)

2

There are 2 best solutions below

2
Gabe Sechan On

You should never make more than one MediaPlayer, they're heavyweight objects and take a lot of resources. Instead, make a single media player, and use setDataSource to change the sound it's set to play (you need to stop the original sound first of course).

Then the next thing to change is to structure your data. Create a map of ids to sounds:

Map<Int, Int> sounds = new HashMap();
sounds.put(button1id, R.raw.hannaba);
sounds.put(button2id, R.raw.mannaba);
...

Then you can have a single click function:

public void buttonClick(View view) {
   mediaPlayer.stop()
   mediaPlayer.setDataSource(sounds.get(view.getId())
   mediaPlayer.start()
}

Set that as the onClickListener of all the buttons you want to act like that, and you only have to write it once.

0
Davit Hovhannisyan On

Try this way:

public void button1Text(View view) {
    if (media2 != null && media2.isPlaying()) {
        media2.stop();
        media2.release();
    }

    media1 = MediaPlayer.create(QuranJ30MA.this, R.raw.hannaba);
    media1.start();
}

public void button2Text(View view) {
    if (media1 != null && media1.isPlaying()) {
        media1.stop();
        media1.release();
    }

    media2 = MediaPlayer.create(QuranJ30MA.this, R.raw.mannaba);
    media2.start();
}