AudioFocus的申请与释放

2017-04-11  本文已影响0人  whstywh

参数一:申请成功后对AudioFocus的监听;
参数二:音频类型
STREAM_ALARM:手机闹铃,STREAM_MUSIC:手机音乐
STREAM_RING:电话铃声,STREAM_SYSTEAM:手机系统
STREAM_DTMF:音调,STREAM_NOTIFICATION:系统提示
STREAM_VOICE_CALL:语音电话
参数三:
AudioManager.AUDIOFOCUS_GAIN:长时间获得AudioFocus
AudioManager.AUDIOFOCUS_LOSS:
长时间失去了Audio Focus,需要停止Audio的播放,并且释放Media资源。为了避免再次自动获得AudioFocus而继续播放,不然突然冒出来的声音会让用户感觉莫名其妙,直接放弃AudioFocus,如果需要再次播放,用户要在界面上点击开始播放,才重新初始化Media,进行播放。
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
暂时失去AudioFocus,并会很快再次获得。必须停止Audio的播放,但是因为是暂时失去AudioFocus,可以不释放Media资源;
AUDIOFOCUS_GAIN_TRANSIENT:暂时获取焦点 适用于短暂的音频
AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:应用跟其他应用共用焦点但播放的时候其他音频会降低音量
返回值:
AUDIOFOCUS_REQUEST_GRANTED:申请成功;
AUDIOFOCUS_REQUEST_FAILED:申请失败;

//获取AudioManager对象
 AudioManager   am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
 
//注册OnAudioFocusChangeListener监听
 AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }

            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                if (mediaPlayer == null) {
                    ...
                } else if (!mediaPlayer.isPlaying()) {

                    mediaPlayer.start();

                }
                // Resume playback
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                if (mediaPlayer.isPlaying()) {

                    mediaPlayer.stop();
                }
                am.abandonAudioFocus(afChangeListener);
            }
        }
    };
 
//在播放的时候为AudioManager添加获取焦点的监听
 int result = mManager.requestAudioFocus(afChangeListener,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mediaPlayer.start();
        }
//在我们不用的时候将焦点释放掉
 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
  am.abandonAudioFocus(afChangeListener);
 }


AudioManager的常用方法


当铃声模式为震动时需要添加权限:
<uses-permission android:name=”android.permission.VIBRATE”/>


上一篇下一篇

猜你喜欢

热点阅读