Search code examples
androidaudioandroid-mediaplayermedia

Problems with Android MediaPlayer


I am making sound application in Android and when I click on button it play sound, it's working good but I have a little problem that I can't solve. When I click on 1 button it play sound, but when I click on second button it also play sound simultaneously and both sounds are played at the same time. How can I prevent this? To play only 1 sound at a time. So I want it to when clicked on 1st button, start playing, when clicked on 2nd button stop sound on 1st button and start playing sound on 2nd button and so on

     final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
  ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
  sound1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (mp.isPlaying()) {
            mp.pause();
            mp.seekTo(0);
        }
        else {
            mp.start();   
        }
    }
});

  //HEKLER
  final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hekler);
  ImageButton sound2=(ImageButton)findViewById(R.id.sound2);
  sound2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(mp2.isPlaying())
        {
mp2.pause();
mp2.seekTo(0);
        }
        else {
            mp2.start();
        }
    }
});

Solution

  •         final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
        final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hekler);
    
        ImageButton sound1 = (ImageButton) findViewById(R.id.sound1);
        sound1.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mp2.isPlaying()) {
                    mp2.pause(); 
                    mp.start();
                } else {
                    mp.start();
                }
            }
        });
    
        ImageButton sound2 = (ImageButton) findViewById(R.id.sound2);
        sound2.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mp.isPlaying()) {
                    mp.pause();
                    mp.seekTo(0);
                    mp2.start();
                } else {
                    mp2.start();
                }
            }
        });