Android Studio two buttons reproduce same file

0

Hello, how are you? I am trying to make a button of sounds in Android Studio and I put two buttons "btn1" and "personasjitos" (I leave the code below) when trying the application any of the two buttons I played the same file, Android Studio I do not mark any error in the code so I do not know what the problem may be, thank you very much for your answers.

public class MainActivity extends AppCompatActivity {
    MediaPlayer mp;
    Button btn1;
    Button personajitos;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.button1);
        personajitos = (Button) findViewById(R.id.personajitos);

        mp = MediaPlayer.create(this, R.raw.peroperopero);
        mp = MediaPlayer.create(this, R.raw.unospersonajitos);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp.start();
            }
        });

        personajitos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp.start();
            }
        });

    }

}
    
asked by Lucas Fajersztejn 25.09.2018 в 06:33
source

1 answer

2

The question is that you first create a MediaPlayer with an audio and then you create it with another one. I recommend that you create the audio at the moment you click each button, that way you will be able to execute the two audios.

public class MainActivity extends AppCompatActivity {
    MediaPlayer mp;
    Button btn1;
    Button personajitos;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.button1);
        personajitos = (Button) findViewById(R.id.personajitos);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp = MediaPlayer.create(MainActivity, R.raw.peroperopero);
                mp.start();
            }
        });

        personajitos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mp = MediaPlayer.create(MainActivity, R.raw.unospersonajitos);
                mp.start();
            }
        });

    }

}

I have put the audios one in each, even if you want them to sound differently. You just have to change the raw you want to execute.

    
answered by 25.09.2018 / 09:06
source