Sartheris Stormhammer
Sartheris Stormhammer

Reputation: 2564

How do I get the system volume programatically

I want to get the system volume level to use programatically, the one you set with the hardware keys when being outside any application. I tried with below method but it doesnt do anything

        MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.notif);
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int volume_level = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
        mediaPlayer.setAudioStreamType(volume_level);
        mediaPlayer.start();

What do I need to change?

Upvotes: 2

Views: 4218

Answers (2)

ARN
ARN

Reputation: 193

You have to change this line

 mediaPlayer.setAudioStreamType(volume_level);

to this:

 mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);

setAudioStreamType()

Used to identify the type of audio stream

AudioManager.STREAM_ALARM is for alarm

AudioManager.STREAM_DTMF is for touch sounds

AudioManager.STREAM_MUSIC is for music

AudioManager.STREAM_NOTIFICATION is for notification

AudioManager.STREAM_RING is for phone ring

AudioManager.STREAM_SYSTEM is for system sounds

AudioManager.STREAM_VOICE_CALL is for phone calls

Upvotes: 4

Himanshu Agarwal
Himanshu Agarwal

Reputation: 4691

Please reffer offical doc here to set or get the system volume of android device.

To set volume level to 20 you can use following code:

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);

Upvotes: -2

Related Questions