Search code examples
android-mediaplayervolumeaudio-playerandroid-music-playerpersistent-volumes

How lower music volume on playing my app voice guidance in Android and after that increase music again?


I am working on an android map app that like Waze or any other app uses voice guidance to guide people to their destination.

My problem is that I want if user play music with his/her phone music volume decrease and voice guidance play with upper volume and after finishing guiding user music volume increase again and get focus of speakers?

Is this can be down I searched a lot and saw some implementation of it but none of them helped me in this special condition.

Thanks all of you in advance.


Solution

  •        AudioManager am = (AudioManager)getContext().getSystemService(AUDIO_SERVICE);
    
     mp = new android.media.MediaPlayer();
                                mp.setDataSource("/data/data/" + getContext().getPackageName() + "/rasa.wav");
                                mp.prepare();
                                mp.start();
                                AudioManager.OnAudioFocusChangeListener focusChangeListener =
                                        focusChange -> {
                            };
                                int result = am.requestAudioFocus(focusChangeListener,
                                        AudioManager.STREAM_MUSIC,
                                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
                                if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                                    mp = new android.media.MediaPlayer();
                                    mp.setOnCompletionListener(mediaPlayer -> {
                                        am.abandonAudioFocus(focusChangeListener);
                                    });
                                    mp.setDataSource("/data/data/" + getContext().getPackageName() + "/rasa.wav");
                                    mp.prepare();
                                    mp.start();
    
                                }