开发者

What is audio focus in Android class AudioManager?

开发者 https://www.devze.com 2023-03-17 12:21 出处:网络
The AudioManager class has a method abandonAudioFocus() and another method requestAudioFocus(). I wonder what is audio focus? And what happens if an AudioManager 开发者_StackOverflow中文版object gets

The AudioManager class has a method abandonAudioFocus() and another method requestAudioFocus(). I wonder what is audio focus? And what happens if an AudioManager 开发者_StackOverflow中文版object gets the audio focus or lost the audio focus?

Thank you!


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.


  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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号