我正在研究一个音乐播放器,该音乐播放器在后台将音乐作为音频服务运行。
假设音乐正在后台通过我的应用播放,并且用户播放了其他应用(例如Youtube)中的另一个媒体文件,然后退出了该应用。这样可以暂停通过我的应用播放的音乐,现在用户必须手动恢复音乐。
如何在外部媒体文件关闭后自动恢复音乐文件?
答案 0 :(得分:2)
我认为您正在寻找控制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;
}
}
}
不过请注意documentation中所述的内容:
永久失去焦点
如果音频焦点丢失是永久的 (AUDIOFOCUS_LOSS),另一个应用正在播放音频。您的应用应该暂停 立即播放,因为它永远不会收到AUDIOFOCUS_GAIN 打回来。要重新开始播放,用户必须采取明确的措施, 例如在通知或应用程序用户界面中按下播放传输控件。
这是假设接收到永久的音频焦点丢失,但是我可以看到一些解决方法,例如轮询音频焦点,但最好不要这样做。如前所述,他们明确指出:
用户必须采取明确的行动