syferlux syferlux - 17 days ago 8
Android Question

how to play different audio on button click android java

I want to play music when a button is clicked, but I want to play different music with different button then the first music stopped and the second music would play.

code:

charge = MediaPlayer.create(this, R.raw.charge);
santai1 = MediaPlayer.create(this, R.raw.santai1);




}

public void charge(View view) {
charge.start();


}

public void santai1(View view) {
santai1.start();

}


Say, I clicked charge button and then played the charge.mp3. Then I want to play santai1.mp3 but when I clicked the santai1 button the charge.mp3 will stop playing and the santai1.mp3 will play.

I want this to be able the opposite and it can be done continuously.

When I clicked santai1 button then santai1.mp3 will be played, while the santai.mp3 still playing I clicked the charge button. I want the santai1.mp3 stopped and then play the chage.mp3.

When I clicked on charge button, then I clicked on santai1 button, both music started together.

Answer

if you need it for many create a mediaplayer object and a method.

private MediaPlayer media;

     private void stopMusic() {
            if (media != null) {
                media.stop();
                media.release();
                media= null;
           }
        }

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               stopMusic();
                    media= MediaPlayer.create("you acivityname".this, "mp3file directory");
                    media.start();
            }
        });