Stop Other Sounds When New Sound is Selected in Android Java

Stop Other Audio Sound When Currently Selected Audio is Playing in Android Studio Java

So if you are working on a sound related android app, like soundboard, ghost sound, cow sounds etc, you will need to disable other sounds while playing currently selected audio, this is important because if other sounds are not disabled while playing a selected audio track, everything will play at the same time when user play another sound button without stopping the current one.

So here is the java code that will stop other sounds and play only the currently selected sound

Create a public MediaPlayer 

public MediaPlayer mp;

 

And then add this code below oncreate

public void playAudio(int audioId)
   {
       // stop the previous playing audio
       if(mp != null && mp.isPlaying())
       {
           mp.stop();
           mp.release();
           mp = null;
       }
       mp = MediaPlayer.create(this, audioId);
       mp.start();
   }

 

Then on button click or onclick, call this code

playAudio(R.raw.airraidsiren);

Replace the airraidsiren with your own audio. So this is it, drop a comment below if you face any error

,

Post navigation

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.