Search code examples
androidmedia-playerplayback

MediaPlayer when clicking on other buttons require 2 clicks to play


I have MediaPlayer in GridView with onItemClickListener with cases. I am using only 1 instance of MediaPlayer for all cases/files. But with the code that I have, this happens: I start mp on 1st button. And I want to play 2nd button. What happens, when I click on 2nd button MP stops and then I have to click again to play it. Is there any way to avoid this?

Here is my code:

if (mPlay.isPlaying()) {
                        mPlay.reset();
                    } else {

                        mPlay = MediaPlayer
                                .create(ActivityM.this, R.raw.sound1);

                        mPlay.start();
                    }

Code is same for all Cases, the only difference is file. I also tried with mPlay.stop(); mPlay.Pause(); mPlay.seekTo(0); etc but same thing happened.


Solution

  • Used Switch Case in your onItemClickListener onItemClick(.....) event like

    grid.setOnItemClickListener(new OnItemClickListener() {
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
    switch(position){
    
        case 0:
         mPlay = MediaPlayer.create(ActivityM.this, R.raw.sound1);
         break;
        case 1:
         mPlay = MediaPlayer.create(ActivityM.this, R.raw.sound2);
         break;
        case 2:
        mPlay = MediaPlayer.create(ActivityM.this, R.raw.sound3);
         break;
        .... so on
        default:
     break; 
     }
      }
    });
    

    Hope this will help you.