syferlux syferlux - 1 year ago 110
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.


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


public void charge(View view) {


public void santai1(View view) {


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 Source

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

private MediaPlayer media;

     private void stopMusic() {
            if (media != null) {
                media= null;

button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                    media= MediaPlayer.create("you acivityname".this, "mp3file directory");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download