0

Below code is working till Oreo but same code is not working in android pie. Please check my code.

int audioFile = R.raw.ring;
mMediaPlayer = new MediaPlayer();
try {

    mMediaPlayer.setDataSource(this,
            Uri.parse("android.resource://com.blh.pickupfresh.resturentapp/" + audioFile));

    final AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_RING,audioManager.getStreamMaxVolume(AudioManager.STREAM_RING),0);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
    mMediaPlayer.setLooping(true);
    mMediaPlayer.prepare();
    mMediaPlayer.start();
} catch (Exception e) {
    e.printStackTrace();
}
Avinash Karn
  • 43
  • 1
  • 7

1 Answers1

0

Try this code

int audioFile = R.raw.ring;

if(mMediaPlayer == null)
    mMediaPlayer = new MediaPlayer();

try {
    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                .build());
    } else {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    mMediaPlayer.setLooping(true);
    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() 
      {
          @Override
          public void onPrepared(MediaPlayer mp) {
               mp.start();
          }
      });

    mMediaPlayer.setDataSource(this, Uri.parse("android.resource://com.blh.pickupfresh.resturentapp/" + audioFile));
    mMediaPlayer.prepareAsync();

} catch (Exception e) {
    e.printStackTrace();
    Log.e(TAG,"ERROR=" + e.getMessage());
}

Here I have used AudioManager.STREAM_MUSIC and also increased volume for the same stream. It will play sound even in Silent mode OR DND.

UPDATE: For Android 9 in some device mMediaPlayer.prepare() takes seconds, so we should use async method with callback and its working.


In android (at least oreo + pie), When Silent mode is ON OR DND mode is ON we can not set AudioManager.STREAM_RING to NORMAL because it will throw an Exception

java.lang.SecurityException: Not allowed to change Do Not Disturb state. See this for further details In Android 7 (API level 24) my app is not allowed to mute phone (set ringer mode to silent)

Naitik Soni
  • 700
  • 8
  • 16