zamroni hamim
zamroni hamim

Reputation: 555

How to set android MediaPlayer volume according to ringtone volume?

How can I set the MediaPlayer sound volume according to ringtone volume?

I did this method, but doesn't work:

        MediaPlayer player = MediaPlayer.create(MyActivity.this, R.raw.sound);
        AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audio.getStreamVolume(AudioManager.RINGER_MODE_NORMAL);

        player.setVolume(currentVolume, currentVolume);

Upvotes: 4

Views: 7004

Answers (4)

Rajesh.k
Rajesh.k

Reputation: 2437

You can try like below:

 AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
            .setLegacyStreamType(AudioManager.STREAM_RING)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build();
    int s = audioManager.generateAudioSessionId();
    mediaPlayer = MediaPlayer.create(context, R.raw.default_ring,audioAttributes,s);
    mediaPlayer.setLooping(true);
    mediaPlayer.start();

You can pass the required stream type in setLegacyStreamType(). if you do like above your media player voulme will follow the stream type volume which is passed to setLegacyStreamType() method in audio attributes.

Upvotes: 2

tsig
tsig

Reputation: 148

Trying to play on AudioManager.STREAM_NOTIFICATION or AudioManager.STREAM_RING didn't produce any sound. I had to go through AudioManager.STREAM_MUSIC. Using the idea of ssuukk at Android: MediaPlayer setVolume function, I wrote the following code that worked:

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume_level1= am.getStreamVolume(AudioManager.STREAM_RING);
int maxVolume=am.getStreamMaxVolume(AudioManager.STREAM_RING);
final MediaPlayer mp1 = MediaPlayer.create(context, R.raw.notification_delivery);
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
float log1=(float)(1-Math.log(maxVolume-volume_level1)/Math.log(maxVolume));
mp1.setVolume(log1,log1);

Upvotes: 1

ianhanniballake
ianhanniballake

Reputation: 199805

Instead of adjusting the volume, you should use setAudioStreamType() to set which audio stream you want to play your audio over - this automatically uses the volume of the selected stream. For example, if you want your audio to play at the same volume as a notification would, you could use AudioManager.STREAM_NOTIFICATION:

mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

Upvotes: 10

Androider
Androider

Reputation: 3873

Try it:

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

Upvotes: 1

Related Questions