Search code examples
androidaudiomedia-player

How do I stop Media Player from playing multiple sounds on top of each other


How do I stop MediaPlayer to play on top of each other? I want my Media Player in application to play only 1 sound. Right now it's when I play 1 sound, and then play another sound they both play at same time. I want when I play 2nd sound, 1st to stop so they don't play on top of each other. My code:

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

        @Override
        public void onClick(View v) {
            if (mp.isPlaying()){
                mp.pause();
                mp.seekTo(0);
            }
            else{
                mp.start();
            }
            }

    });

    mp2=MediaPlayer.create(this, R.raw.dragunov);
    ImageButton dugme2 = (ImageButton) findViewById(R.id.dugme2);
    dugme2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mp2.isPlaying()){
                mp2.pause();
                mp2.seekTo(0);
            }
            else{
                mp2.start();
            }
            }

    });

    mp3=MediaPlayer.create(this, R.raw.g3s);
    ImageButton dugme3= (ImageButton) findViewById(R.id.dugme3);
    dugme3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mp3.isPlaying()){
                mp3.pause();
                mp3.seekTo(0);
            }
            else{
                mp3.start();
            }
            }

    });
    mp4=MediaPlayer.create(this, R.raw.psg1);
    ImageButton dugme4= (ImageButton) findViewById(R.id.dugme4);
    dugme4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mp4.isPlaying()){
                mp4.pause();
                mp4.seekTo(0);
            }
            else{
                mp4.start();
            }
            }

    });

    mp5=MediaPlayer.create(this, R.raw.scout);
    ImageButton dugme5= (ImageButton) findViewById(R.id.dugme5);
    dugme5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mp5.isPlaying()){
                mp5.pause();
                mp5.seekTo(0);
            }
            else{
                mp5.start();
            }
            }

    });
}

}


Solution

  • You are only checking if your current mediaplayer is playing or not, that is, in mp, you are only checking mp, and so on.

    You need to stop/pause all other MediaPlayers before you start playing one of them. Before starting any of them, check if any of the other four are running. If they are, then stop/pause them and after doing this for all playing media players, start the current media player.