0
votes

I have audios which only play when certain conditions are met. I want to increase the audio volume only when it plays, and once it finishes the volume should be set to default system volume. Currently I am setting volume to max, which works ok when audio is playing but keeps the system volume to that level even after audios are finished. Which makes a very bad situation for user when say a call comes it makes the device very noisy. I am confused to achieve this. I have also read that using audioManager to set volume is not a good practice and it has side effects.

Here is something which I was trying to control the volume:

public void resume() {

        AudioManager audioManager = (AudioManager) MobieFitSdkApplication.singleton().getSystemService(Context.AUDIO_SERVICE);
        if (player != null) {
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
            player.setVolume(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        }

    }

So how can I only increase volume when audios are playing?

2
check thisHemant Parmar

2 Answers

0
votes

-Do one thing first of all get the current volume of System:

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume_level= am.getStreamVolume(AudioManager.STREAM_MUSIC);

after your audio complete or when you release media player at that time set the default volume which you get before the audio play.

am.setStreamVolume(AudioManager.STREAM_MUSIC,volume_level,0);
0
votes

I have achieved what I have asked in my question by taking some help from the above answers.

First I am getting the original system volume and once the audio starts I am setting the system volume to 70%.

int originalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    int maxDeviceVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                    float percent = 0.7f;
                    int seventyVolume = (int) (maxDeviceVolume*percent);
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);

Once the audio ends I am resetting the device volume to the original.

mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0);