Android-Android的OnAudioFocusChangeListener这个方法要怎么用?
经过研究Android声音处理上需要处理audiofocus的争夺问题,翻了很久的网页也没有发现网上有关于这个问题的处理dome,现在只知道需要一个OnAudioFocusChangeListener方法来获取处理.请问这个方法具体要怎么用呢?希望能给一个简单的完整的dome(例如用mediaplayer播放音频要怎么传递消息?怎么调小声音,背后依然播放?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你又到这提问了,我就再把我的解答复制一份好了。
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里面实现的,你自己试试看吧