3

我正在开发一个音乐播放器,它在后台将音乐作为音频服务运行。

假设音乐正在后台通过我的应用程序播放,用户从其他应用程序(例如:Youtube)播放另一个媒体文件,然后退出该应用程序。这会暂停通过我的应用程序播放的音乐,现在用户必须手动恢复音乐。

外部媒体文件关闭后如何自动恢复音乐文件?

4

1 回答 1

3

我认为您正在寻找控制Audio Focus。这讨论了当另一个应用程序/您的应用程序控制音频焦点时如何实现更改,即增益调整(降低音量)。

mAudioManager = (AudioManager) Context.getSystemService(Context.AUDIO_SERVICE);
mPlaybackAttributes = new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_GAME)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build();
mFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
        .setAudioAttributes(mPlaybackAttributes)
        .setAcceptsDelayedFocusGain(true)
        .setOnAudioFocusChangeListener(mMyFocusListener, mMyHandler)
        .build();
mMediaPlayer = new MediaPlayer();
final Object mFocusLock = new Object();

boolean mPlaybackDelayed = false;
boolean mPlaybackNowAuthorized = false;

// ...
int res = mAudioManager.requestAudioFocus(mFocusRequest);
synchronized(mFocusLock) {
    if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
        mPlaybackNowAuthorized = false;
    } else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mPlaybackNowAuthorized = true;
        playbackNow();
    } else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
       mPlaybackDelayed = true;
       mPlaybackNowAuthorized = false;
    }
}

// ...
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            if (mPlaybackDelayed || mResumeOnFocusGain) {
                synchronized(mFocusLock) {
                    mPlaybackDelayed = false;
                    mResumeOnFocusGain = false;
                }
                playbackNow();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS:
            synchronized(mFocusLock) {
                mResumeOnFocusGain = false;
                mPlaybackDelayed = false;
            }
            pausePlayback();
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            synchronized(mFocusLock) {
                mResumeOnFocusGain = true;
                mPlaybackDelayed = false;
            }
            pausePlayback();
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // ... pausing or ducking depends on your app
            break;
        }
    }
}

但是请注意,如文档中所述:

永久失去焦点

如果音频焦点丢失是永久性的 (AUDIOFOCUS_LOSS),则另一个应用正在播放音频。您的应用应立即暂停播放,因为它永远不会收到 AUDIOFOCUS_GAIN 回调。要重新开始播放,用户必须采取明确的操作,例如在通知或应用 UI 中按下播放传输控件。

这是假设收到永久音频焦点丢失,但是我可以看到一些解决方法,例如轮询音频焦点,但最好不要这样做。如前所述,他们已明确表示:

用户必须采取明确的行动

于 2018-07-06T13:40:27.190 回答