What is audio focus in Android class AudioManager?

前端 未结 3 1722
既然无缘
既然无缘 2021-01-11 12:39

The AudioManager class has a method abandonAudioFocus() and another method requestAudioFocus(). I wonder what is audio focus? And what

相关标签:
3条回答
  • 2021-01-11 13:17

    You use audio focus when setting which app has the playback priority. For example, you can set up what should your app do when it's playing a audio file and some other app wants to take the focus and play something. If you do not set up what will happen it these cases, the other app will just play audio over yours. I've written a blog post about this: http://markojerkic.com/handling-audio-focus-in-android/

    0 讨论(0)
  • 2021-01-11 13:23
      AudioManager am = (AudioManager)getContext().getSystemService(AUDIO_SERVICE);
                            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();
                            }
    
    0 讨论(0)
  • 2021-01-11 13:39

    It has to do with priority when using the speakers, to prevent playing many things at once or being overridden. If you requestAudioFocus(), you're declaring that you want control. You can then listen with onAudioFocusChange(int focusChange) to see if anything else tries to play a sound. You may forcefully lose focus (like during a phone call) but then you can gain it later. You should abandonAudioFocus() when you're finished.

    0 讨论(0)
提交回复
热议问题