Android-Android的OnAudioFocusChangeListener这个方法要怎么用?

发布于 2017-02-03 06:58:32 字数 187 浏览 1165 评论 1

经过研究Android声音处理上需要处理audiofocus的争夺问题,翻了很久的网页也没有发现网上有关于这个问题的处理dome,现在只知道需要一个OnAudioFocusChangeListener方法来获取处理.请问这个方法具体要怎么用呢?希望能给一个简单的完整的dome(例如用mediaplayer播放音频要怎么传递消息?怎么调小声音,背后依然播放?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虐人心 2017-04-13 12:08:27

你又到这提问了,我就再把我的解答复制一份好了。

Android中有个AudioFocus的概念,你可以为Music去监听AudioFocus。
这个问题一下子说不清楚,建议先看下http://developer.android.com/training/managing-audio/audio-focus.html,这里面介绍了一些Audio focus的基本概念。希望对你有帮助!

补充一下:

(1)在Call Play之前要获取Audio Focus

mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

(2)具体AudioFocus Listener的实现

private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
// AudioFocus is a new feature: focus updates are made verbose on purpose
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
Log.v(TAG, "AudioFocus: received AUDIOFOCUS_LOSS");
if(mLocalPlayer.isPlaying()) {
mLocalPlayer.pause();
}
if (mMediaplayerHandler != null && mMediaplayerHandler.hasMessages(FADEIN)) {
mMediaplayerHandler.removeMessages(FADEIN);
mPlayer.setVolume(1.0f);
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.v(TAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
if(mLocalPlayer.isPlaying()) {
mLocalPlayer.pause();
}

if (mMediaplayerHandler != null && mMediaplayerHandler.hasMessages(FADEIN)) {
mMediaplayerHandler.removeMessages(FADEIN);
mPlayer.setVolume(1.0f);
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.v(TAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
if(mLocalPlayer.isPlaying()) {
mPlayer.setVolume(0.0f);
Log.d(TAG, "Mute since received AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.v(TAG, "AudioFocus: received AUDIOFOCUS_GAIN");
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
boolean isPhoneHook = false;
if (tm != null) {
isPhoneHook = (tm.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK);
}
if(!mLocalPlayer.isPlaying() && mPausedByTransientLossOfFocus) {
mPausedByTransientLossOfFocus = false;
if (!isPhoneHook) {
startAndFadeIn();
}
} else if (mMuteByTransientLossOfFocusCanDuck) {
mMuteByTransientLossOfFocusCanDuck = false;
if (!isPhoneHook) {
mPlayer.setVolume(1.0f);
}
Log.d(TAG, "Unmute since received AUDIOFOCUS_GAIN");
}
break;
default:
Log.e(TAG, "Unknown audio focus change code");
}
}
};

(3)在Activity OnDestory的时候释放AudioFocus.

 mAudioManager.abandonAudioFocus(mAudioFocusListener);

(4)这只是一个简单的Main Thread实现的例子,真正的做Music是要在Service里面实现的,你自己试试看吧

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文