Search code examples
javaandroidaudioandroid-mediaplayermedia

Media Player won't play the sound in button click method


I have 3 buttons and they are supposed to play 3 different sounds. When I used 3 separate onclicks methods in oncreate method it worked properly, but I wanted to clean the code a little, so I implemented OnClickListener to acvtivity and moved the onclick methods down. But now, media players don't play the sounds. How can I make sure media players work?

public class Play extends Activity implements OnClickListener {

    MediaPlayer mpPlay1,mpPlay2,mpPlay3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play);


    Button bPlay1 = (Button) findViewById(R.id.button1);
    Button bPlay2 = (Button) findViewById(R.id.button2);
    Button bPlay3 = (Button) findViewById(R.id.button3);

        int resIdPlay1 = getResources().getIdentifier("play1", "raw", getPackageName());
        int resIdPlay2 = getResources().getIdentifier("play2", "raw", getPackageName());
        int resIdPlay3 = getResources().getIdentifier("play3", "raw", getPackageName());

        mpPlay1 = MediaPlayer.create(this, resIdPlay1);
        mpPlay2 = MediaPlayer.create(this, resIdPlay2);
        mpPlay3 = MediaPlayer.create(this, resIdPlay3);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.button1:
            mpPlay1.start();
            break;
        case R.id.button2:
            mpPlay2.start();
            break;
        case R.id.button3:
            mpPlay3.start();
            break;

        }

    }

}

Solution

  • You haven't implemented the listener on the Buttons yet, or at least haven't shown it. You should have something like

    Button btn1 = (Button) findViewById(R.id.button1);
    btn1.setOnClickListener(this);
    

    inside your onCreate() after setContentView(). You would need this for each Button.

    Since you are trying to clean up your code and make it more condensed, you can set the onClick() in your xml.

    I have explained it in this answer and this one

    The Button docs also cover this