Which method to get the full volume of media on Android?

4

My application needs the user to choose at startup whether they want to hear the sounds of the app or not, as it is an application to also be used in the classroom and in that environment the volume of the app must be zeroed. >

So I created a AlertDialog so once the app is run the user decides whether or not to lower the volume, like this:

AlertDialog.Builder dlg = new AlertDialog.Builder(ActDinamica.this);
    dlg.setTitle("Bem Vindo!");
    dlg.setMessage("Você está em aula?");
    dlg.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Mute();
        }
    });
    dlg.setNegativeButton("Não", null);
    dlg.show();

So I need to set this Mute(); method so that the volume of the cell phone's media audio goes to zero.

Method:

private void Mute() {
    // codigo para o volume zerar?
}

Note: I found only methods to stop specific audios that were being executed ...

    
asked by anonymous 31.01.2017 / 16:37

2 answers

2

You should use the AudioManager , which is a public class, which provides volume access and ringer mode control. Here's an example of how it can be used by setting a specific volume with the setStreamVolume() method:

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

For your case you can set it to 0 once AlertDialog appears. See:

private void Mute() {
    AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
}

Check documentation for more details.

    
31.01.2017 / 17:48
2

In your Manifest.xml file, you must add permission to vibrate.

<uses-permission android:name="android.permission.VIBRATE" />

To mute the cell, you can fire AudioManager as follows:

AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

And to recover the volume, you can do it as follows:

AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);

audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
    
31.01.2017 / 17:38