How NOT to play sounds when phone is muted? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How NOT to play sounds when phone is muted? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am making an app using a MediaPlayer object to play a sound every time a function gets called. However, this sound is playing even though the phone is muted. How can I avoid this?

This is basically the code I have

private lateinit var mediaPlayer: MediaPlayer

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mediaPlayer = MediaPlayer.create(this, R.raw.bruh)
        ...
}

private fun getRandomAnswer(){
        ...
        mediaPlayer.start()

}

Answer

In your method check if phone is in silent mode by AudioManager code and you can set volume to 0 if it’s in vibrate or silent mode,

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

switch (am.getRingerMode()) {
  case AudioManager.RINGER_MODE_SILENT:
    //Silent mode set media volume to 0 if playing
    mediaPlayer setVolume(0,0);
    break;
  case AudioManager.RINGER_MODE_VIBRATE:
    //vibrate mode set media volume to 0 if playing
    mediaPlayer.setVolume(0,0);
    break;
  case AudioManager.RINGER_MODE_NORMAL:
    //normal mode
    mediaPlayer.setVolume(1,1);
    break;
}
We are here to answer your question about How NOT to play sounds when phone is muted? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji