如何防止 android studio 中我的应用程序的音乐播放器声音和背景声音发生冲突

how to prevent clashes of music player sound and background sound of my app in android studio

我正在使用后台服务开发一个带有背景声音的应用程序,所以问题是我是 运行 我的应用程序,如果我的音乐播放器是 运行 - 两个声音冲突彼此。

我的问题:如何防止我的应用程序的音乐播放器声音和背景声音发生冲突

actual: music clashes with each other.

expected: if player is running it must be pause and background sound of my app is only plays.

如果您连续播放背景音,则必须request audio focus by calling requestAudioFocus(). This informs the other app that you would like to play something and that they should stop (in the case where you request AUDIOFOCUS_GAIN合适。

请注意,requestAudioFocus 要求您传入 OnAudioFocusChangeListener - 就像其他应用一样,您应该 尊重其他应用请求音频焦点和停止背景音。

注意:您还应该始终提供关闭背景声音的功能(以及任何对音频焦点的请求)。这允许用户即使在您的应用程序中也能继续收听他们的音乐。

我是如何解决这个问题的,我只是通过停止音乐播放器和播放应用程序背景音乐来解决两首音乐的冲突。

AudioManager.OnAudioFocusChangeListener afChangeListener;

AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

                    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        // Start playback.
                        mPlayer.setLooping(true);
                        final float volume = (float) (1 - (Math.log(MAX_VOLUME - 85) / Math.log(MAX_VOLUME)));
                        mPlayer.setVolume(volume, volume);
                        mPlayer.start();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

注意:代码仅适用于停止音乐,不适用于恢复音乐。