AudioFocus

在使用AudioFocus获取音频焦点时,这两个参数都可以获取焦点。但两个参数的解释却不一样
public static final int AUDIOFOCUS_GAIN
Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
获取后不release,需要手动release
public static final int AUDIOFOCUS_GAIN_TRANSIENT   视频播放可以用此参数,播放完就失去焦点。
Used to indicate a temporary gain or request of audio focus, anticipated to last a short amount of time. Examples of temporary changes are the playback of driving directions, or an event notification.
临时获取,使用后release 所以拍照时候“咔”应该使用AUDIOFOCUS_GAIN_TRANSIENT

 

     AUDIOFOCUS_GAIN:获得了Audio Focus;
     AUDIOFOCUS_LOSS:失去了Audio Focus,并将会持续很长的时间。这里因为可能会停掉很长时间,所以不仅仅要停止Audio的播放,最好直接释放掉Media资源。而因为停止播放Audio的时间会很长,如果程序因为这个原因而失去AudioFocus,最好不要让它再次自动获得AudioFocus而继续播放,不然突然冒出来的声音会让用户感觉莫名其妙,感受很不好。这里直接放弃AudioFocus,当然也不用再侦听远程播放控制【如下面代码的处理】。要再次播放,除非用户再在界面上点击开始播放,才重新初始化Media,进行播放。
     AUDIOFOCUS_LOSS_TRANSIENT:暂时失去Audio Focus,并会很快再次获得。必须停止Audio的播放,但是因为可能会很快再次获得AudioFocus,这里可以不释放Media资源;
     AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:暂时失去AudioFocus,但是可以继续播放,不过要在降低音量。

 

//frameworks/base/media/java/android/media/AudioManager.java
/** * Request audio focus. * Send a request to obtain the audio focus * @param l the listener to be notified of audio focus changes * @param streamType the main audio stream type affected by the focus request * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request * is temporary, and focus will be abandonned shortly. Examples of transient requests are * for the playback of driving directions, or notifications sounds. * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for * the previous focus owner to keep playing if it ducks its audio output. * Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request * that benefits from the system not playing disruptive sounds like notifications, for * usecases such as voice memo recording, or speech recognition. * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such * as the playback of a song or a video. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED} */ public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) { int status = AUDIOFOCUS_REQUEST_FAILED; if ((durationHint < AUDIOFOCUS_GAIN) || (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)) { Log.e(TAG, "Invalid duration hint, audio focus request denied"); return status; } registerAudioFocusListener(l); //TODO protect request by permission check? IAudioService service = getService(); try { status = service.requestAudioFocus(streamType, durationHint, mICallBack, mAudioFocusDispatcher, getIdForAudioFocusListener(l), mContext.getOpPackageName() /* package name */); } catch (RemoteException e) { Log.e(TAG, "Can't call requestAudioFocus() on AudioService due to "+e); } return status; }

 

 

package com.example.tttt;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    private static final String TAG = "CM-MainActivity";
    private AudioManager mAudioManager = null;
    private MediaPlayer mMediaPlayer;

    private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            Log.d(TAG, "onAudioFocusChange()11111 focusChange: " + focusChange);
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    mMediaPlayer.pause();
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    mMediaPlayer.start();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        Log.d(TAG, "onCreate()");
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy()");
        super.onDestroy();
        mAudioManager.abandonAudioFocus(mAudioFocusListener);
        
        mMediaPlayer.reset();
        mMediaPlayer.release();
        // ComponentName componentName = new ComponentName(getPackageName(),
        // MainActivity.class.getName());
        // mAudioManager.unregisterMediaButtonEventReceiver(componentName);
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause()");
        super.onPause();
    }

    @Override
    protected void onRestart() {
        Log.d(TAG, "onRestart()");
        super.onRestart();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume()");
        super.onResume();

        if (mAudioManager != null) {
            //mAudioFocusListener只监听失去焦点或者再次获得焦点时的事件
//本次申请事件是不被mAudioFocusListener处理的
int i = mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); Log.d(TAG, "mAudioManager != null result:" + i); if (i == AudioManager.AUDIOFOCUS_GAIN) { mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource("/storage/sdcard0/jyly.mp3"); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (IOException e) { Log.d(TAG, "error"); e.printStackTrace(); } } else { Log.d(TAG, "request error"); } } else { Log.d(TAG, "mAudioManager == null"); } // ComponentName componentName = new ComponentName(getPackageName(), // MainActivity.class.getName()); // mAudioManager.registerMediaButtonEventReceiver(componentName); } @Override protected void onStart() { Log.d(TAG, "onStart()"); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop()"); super.onStop(); } }

 

posted @ 2015-03-25 09:41  牧 天  阅读(1043)  评论(0)    收藏  举报