Android之音頻焦點(diǎn)
車機(jī)開發(fā)很多應(yīng)用涉及到音頻颤诀,音頻焦點(diǎn)踩過(guò)很多坑谜慌,也填過(guò)很多坑然想,藍(lán)牙,多媒體音視頻畦娄,ipod,收音機(jī)又沾,導(dǎo)航...很多功能都需要對(duì)音頻做響應(yīng)的處理弊仪。如果我們每個(gè)人都按照自己的想法去處理音頻焦點(diǎn)的話熙卡,整個(gè)邏輯就非常的混亂,還好Android有一套比較規(guī)范的音頻焦點(diǎn)處理邏輯及其方法励饵。
直接上關(guān)鍵源碼驳癌。由于項(xiàng)目的源碼不方便提取出來(lái)所以就但是寫了個(gè)服務(wù),核心內(nèi)容都寫在這個(gè)內(nèi)里面役听。
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.os.IBinder;
public class AudioService extends Service{
private AudioManager mAudioManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
initData();
super.onCreate();
}
private void initData() {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
public boolean requestFocus(){
if(afChanggeListener != null ){
/**
* requestAudioFocus()方法的三個(gè)參數(shù)
* 第一個(gè)參數(shù)颓鲜,音頻焦點(diǎn)變化時(shí)的監(jiān)聽器
* 第二個(gè)參數(shù),音頻類型典予,包含AUDIO_STREAM_MUSIC ,AUDIO_STREAM_ALARM ...
* 第三個(gè)參數(shù)甜滨,音頻焦點(diǎn)類型,AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK瘤袖,AUDIOFOCUS_GAIN...
*/
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus(afChanggeListener, AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
}
return false;
}
public boolean abandonFocus(){
if(afChanggeListener != null){
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.abandonAudioFocus(afChanggeListener);
}
return false;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
//適當(dāng)?shù)臅r(shí)候注銷監(jiān)聽器
abandonFocus();
super.onDestroy();
}
OnAudioFocusChangeListener afChanggeListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
//長(zhǎng)時(shí)間的失去焦點(diǎn),注意結(jié)束相關(guān)音頻播放同時(shí)釋放資源
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
//短暫的失去音頻焦點(diǎn)衣摩,但是你可以與新的使用者共同使用音頻焦點(diǎn)(混音輸出)
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
//短暫的失去音頻焦點(diǎn)并且會(huì)很快再次獲得,你可以執(zhí)行暫停操作捂敌,不用釋放資源
break;
case AudioManager.AUDIOFOCUS_GAIN:
//獲得(或者重新獲得)音頻焦點(diǎn)艾扮。
break;
}
}
};
}