android录音时关闭第三方音乐

     摘自 :http://blog.csdn.net/chenchuntong/article/details/8813719

     开始录音的调用方法:

  requestAudioFocus();

     结束录音释放掉焦点

 abandonAudioFocus();

整理代码如下:

private boolean mAudioFocus;
AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {

    public void onAudioFocusChange(int focusChange) {

        switch (focusChange) {

            case AudioManager.AUDIOFOCUS_GAIN:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN");

                mAudioFocus = true;
                requestAudioFocus();
                break;

            case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT");

                mAudioFocus = true;
                requestAudioFocus();
                break;

            case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK");

                mAudioFocus = true;
                requestAudioFocus();
                break;

            case AudioManager.AUDIOFOCUS_LOSS:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS");

                mAudioFocus = false;

                abandonAudioFocus();

                break;

            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT");

                mAudioFocus = false;

                abandonAudioFocus();

                break;

            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:

                Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");

                mAudioFocus = false;

                abandonAudioFocus();

                break;

            default:

                Log.i(TAG, "AudioFocusChange focus = " + focusChange);

                break;

        }

    }

};


private void requestAudioFocus() {

    Log.v(TAG, "requestAudioFocus mAudioFocus = " + mAudioFocus);

    if (!mAudioFocus) {

        int result = mAudioManager.requestAudioFocus(afChangeListener,

                AudioManager.STREAM_MUSIC, // Use the music stream.

                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {

            mAudioFocus = true;

        } else {

            Log.e(TAG, "AudioManager request Audio Focus result = " + result);

        }

    }

}

private void abandonAudioFocus() {

    Log.v(TAG, "abandonAudioFocus mAudioFocus = " + mAudioFocus);

    if (mAudioFocus) {

        mAudioManager.abandonAudioFocus(afChangeListener);

        mAudioFocus = false;

    }

}
@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    mAudioManager.abandonAudioFocus(afChangeListener);

}

你可能感兴趣的:(android录音时关闭第三方音乐)