一、按鍵音調用流程
摘要:按鍵音播放的總體邏輯是先找到系統中按鍵音的資源,然後調用SoundPool.load讓系統加載音頻資源,加載成功後在onLoadComplete回調中會返回一個非0的soundID ,用於播放時指定特定的音頻,最後在需要播放按鍵音的時候直接根據soundID播放
1.Android按鍵音接口
Android按鍵音只有兩個常用接口,分別是:
- 原生設置APP中SoundFragment.java調用的設置按鍵音開關的接口:mAudioManager.loadSoundEffects()和mAudioManager.unloadSoundEffects()
private void setSoundEffectsEnabled(boolean enabled) {
mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); //1
if (enabled) {
mAudioManager.loadSoundEffects();
} else {
mAudioManager.unloadSoundEffects();
}
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.SOUND_EFFECTS_ENABLED, enabled ? 1 : 0);
}
先調用AudioManager的loadSoundEffects方法,然後會調用到AudioService的loadSoundEffects方法
- View.java中播放按鍵音的接口:playSoundEffect
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);//調用會經過ViewRootImpl.java,最終調用到AudioService中
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
最終會調用到AudioService的playSoundEffect方法
2.onLoadSoundEffects()方法
上述的兩個方法調用到AudioService之後,分別通過sendMsg向handler發送MSG_LOAD_SOUND_EFFECTS和MSG_PLAY_SOUND_EFFECT信息,handler在收到信息後會進行相應的操作,但是不管是哪個操作,都會調用到onLoadSoundEffects()方法
loadSoundEffects的調用流程(非重點):
public boolean loadSoundEffects() {
int attempts = 3;
LoadSoundEffectReply reply = new LoadSoundEffectReply();
synchronized (reply) {
//調用sendMsg方法
sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, reply, 0);
while ((reply.mStatus == 1) && (attempts-- > 0)) {
try {
reply.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
} catch (InterruptedException e) {
Log.w(TAG, "loadSoundEffects Interrupted while waiting sound pool loaded.");
}
}
}
return (reply.mStatus == 0);
}
//sendMsg方法是對handler.sendMessageAtTime的封裝
private static void sendMsg(Handler handler, int msg,
int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
if (existingMsgPolicy == SENDMSG_REPLACE) {
handler.removeMessages(msg);
} else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
return;
}
synchronized (mLastDeviceConnectMsgTime) {
long time = SystemClock.uptimeMillis() + delay;
if (msg == MSG_SET_A2DP_SRC_CONNECTION_STATE ||
msg == MSG_SET_A2DP_SINK_CONNECTION_STATE ||
msg == MSG_SET_HEARING_AID_CONNECTION_STATE ||
msg == MSG_SET_WIRED_DEVICE_CONNECTION_STATE ||
msg == MSG_A2DP_DEVICE_CONFIG_CHANGE ||
msg == MSG_BTA2DP_DOCK_TIMEOUT) {
if (mLastDeviceConnectMsgTime >= time) {
// add a little delay to make sure messages are ordered as expected
time = mLastDeviceConnectMsgTime + 30;
}
mLastDeviceConnectMsgTime = time;
}
handler.sendMessageAtTime(handler.obtainMessage(msg, arg1, arg2, obj), time);
}
}
//在handleMessage中處理消息
@Override
public void handleMessage(Message msg) {
......
case MSG_PLAY_SOUND_EFFECT:
//調用onPlaySoundEffect
onPlaySoundEffect(msg.arg1, msg.arg2);
break;
}
private void onPlaySoundEffect(int effectType, int volume) {
synchronized (mSoundEffectsLock) {
//最終會調用到onLoadSoundEffects
onLoadSoundEffects();
......
}
playSoundEffect的調用流程(非重點):
public void playSoundEffect(int effectType) {
playSoundEffectVolume(effectType, -1.0f);
}
public void playSoundEffectVolume(int effectType, float volume) {
// do not try to play the sound effect if the system stream is muted
if (isStreamMutedByRingerOrZenMode(STREAM_SYSTEM)) {
return;
}
if (effectType >= AudioManager.NUM_SOUND_EFFECTS || effectType < 0) {
Log.w(TAG, "AudioService effectType value " + effectType + " out of range");
return;
}
sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_QUEUE,
effectType, (int) (volume * 1000), null, 0);
}
//在handleMessage中處理消息
@Override
public void handleMessage(Message msg) {
......
case MSG_PLAY_SOUND_EFFECT:
onPlaySoundEffect(msg.arg1, msg.arg2);
break;
}
private void onPlaySoundEffect(int effectType, int volume) {
synchronized (mSoundEffectsLock) {
onLoadSoundEffects();
......
}
如上所述最終都會調用onLoadSoundEffects方法
在onLoadSoundEffects方法中主要完成以下幾件事:
- 調用loadTouchSoundAssets方法解析XML文件,獲得音源文件名,初始化數組,將音源文件與數組中元素一一對應
- 補全音源文件路徑,調用SoundPool.load方法
- 將SoundPool.load方法返回的sampleId保存在數組中,作爲之後play方法的參數
先來看loadTouchSoundAssets方法,代碼如下:
private void loadTouchSoundAssets() {
XmlResourceParser parser = null;
// only load assets once.
//SOUND_EFFECT_FILES是一個存放字符串的List,裏面存放的是音頻資源的名稱
if (!SOUND_EFFECT_FILES.isEmpty()) {
return;
}
//此方法執行:
//1.SOUND_EFFECT_FILES.add("Effect_Tick.ogg"); 向SOUND_EFFECT_FILES添加一個音頻資源的名稱
//2.初始化一個二維數組SOUND_EFFECT_FILES_MAP。行數爲10,列數爲2,第一列都爲0,第二列都爲-1
loadTouchSoundAssetDefaults();
try {
//獲得XML對象
parser = mContext.getResources().getXml(com.android.internal.R.xml.audio_assets);
XmlUtils.beginDocument(parser, TAG_AUDIO_ASSETS);
//getAttributeValue方法用於獲取傳入的Attribute名稱對應的Value,這裏是"1.0"
String version = parser.getAttributeValue(null, ATTR_VERSION);
boolean inTouchSoundsGroup = false;
if (ASSET_FILE_VERSION.equals(version)) {
while (true) {
//nextElement方法用於切換到XML的下一層
XmlUtils.nextElement(parser);
//獲取當前parser的名稱,這裏是"group"
String element = parser.getName();
if (element == null) {
break;
}
if (element.equals(TAG_GROUP)) {
String name = parser.getAttributeValue(null, ATTR_GROUP_NAME);
if (GROUP_TOUCH_SOUNDS.equals(name)) {
inTouchSoundsGroup = true;
break;
}
}
}
//遍歷XML中剩下的所有元素
while (inTouchSoundsGroup) {
XmlUtils.nextElement(parser);
String element = parser.getName();
if (element == null) {
break;
}
if (element.equals(TAG_ASSET)) {
String id = parser.getAttributeValue(null, ATTR_ASSET_ID);
String file = parser.getAttributeValue(null, ATTR_ASSET_FILE);
int fx;
try {
//getField的對象是.class文件(.java文件的預編譯產物,只進行一些變量即宏的替換),這裏即AudioManager.class
//根據傳入的id獲得AudioManager.class中對應的對象,例如傳入的是"FX_KEY_CLICK",得到的是AudioManager中定義的public static final int FX_KEY_CLICK = 0
Field field = AudioManager.class.getField(id);
fx = field.getInt(null);
} catch (Exception e) {
Log.w(TAG, "Invalid touch sound ID: "+id);
continue;
}
//根據之前XML中讀取的file取出其在SOUND_EFFECT_FILES的位置
//此時SOUND_EFFECT_FILES只有一個元素即"Effect_Tick.ogg"
//如果不存在則加入到SOUND_EFFECT_FILES中
int i = SOUND_EFFECT_FILES.indexOf(file);
if (i == -1) {
i = SOUND_EFFECT_FILES.size();
SOUND_EFFECT_FILES.add(file);
}
SOUND_EFFECT_FILES_MAP[fx][0] = i;
} else {
break;
}
}
}
} catch (Resources.NotFoundException e) {
Log.w(TAG, "audio assets file not found", e);
} catch (XmlPullParserException e) {
Log.w(TAG, "XML parser exception reading touch sound assets", e);
} catch (IOException e) {
Log.w(TAG, "I/O exception reading touch sound assets", e);
} finally {
if (parser != null) {
parser.close();
}
}
}
private void loadTouchSoundAssetDefaults() {
SOUND_EFFECT_FILES.add("Effect_Tick.ogg");
for (int i = 0; i < AudioManager.NUM_SOUND_EFFECTS; i++) {
SOUND_EFFECT_FILES_MAP[i][0] = 0;
SOUND_EFFECT_FILES_MAP[i][1] = -1;
}
}
經過loadTouchSoundAssets初始化後,SOUND_EFFECT_FILES數組爲:
{
"Effect_Tick.ogg" , "KeypressStandard.ogg" , "KeypressSpacebar.ogg" ,
"KeypressDelete.ogg" , "KeypressReturn.ogg" , "KeypressInvalid.ogg" }
SOUND_EFFECT_FILES_MAP數組爲:
{
{
0, -1}, {
0, -1}, {
0, -1}, {
0, -1}, {
0, -1}, {
1, -1}, {
2, -1}, {
3, -1}, {
4, -1}, {
5, -1}}
再來看真正的onLoadSoundEffects方法:
private boolean onLoadSoundEffects() {
int status;
synchronized (mSoundEffectsLock) {
if (!mSystemReady) {
Log.w(TAG, "onLoadSoundEffects() called before boot complete");
return false;
}
if (mSoundPool != null) {
return true;
}
loadTouchSoundAssets();//根據XML文件初始化數組,如上所述
//初始化SoundPool
mSoundPool = new SoundPool.Builder()
.setMaxStreams(NUM_SOUNDPOOL_CHANNELS)
.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build())
.build();
mSoundPoolCallBack = null;
mSoundPoolListenerThread = new SoundPoolListenerThread();
//這個線程以及下面的代碼主要是去設置SoundPoolCallback,不求甚解
mSoundPoolListenerThread.start();
int attempts = 3;
while ((mSoundPoolCallBack == null) && (attempts-- > 0)) {
try {
// Wait for mSoundPoolCallBack to be set by the other thread
mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
}
}
if (mSoundPoolCallBack == null) {
Log.w(TAG, "onLoadSoundEffects() SoundPool listener or thread creation error");
if (mSoundPoolLooper != null) {
mSoundPoolLooper.quit();
mSoundPoolLooper = null;
}
mSoundPoolListenerThread = null;
mSoundPool.release();
mSoundPool = null;
return false;
}
/*
* poolId table: The value -1 in this table indicates that corresponding
* file (same index in SOUND_EFFECT_FILES[] has not been loaded.
* Once loaded, the value in poolId is the sample ID and the same
* sample can be reused for another effect using the same file.
*/
//創建一個和SOUND_EFFECT_FILES一樣大的數組並將元素初始化爲-1
int[] poolId = new int[SOUND_EFFECT_FILES.size()];
for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.size(); fileIdx++) {
poolId[fileIdx] = -1;
}
/*
* Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
* If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
* this indicates we have a valid sample loaded for this effect.
*/
int numSamples = 0;
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
// Do not load sample if this effect uses the MediaPlayer
if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
continue;
}
//第一次走到這裏時這個判斷一定爲真,因爲poolId中所有元素都爲-1
if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
//getSoundEffectFilePath會根據SOUND_EFFECT_FILES中的內容補全出音頻文件的具體路徑
String filePath = getSoundEffectFilePath(effect);
//調用SoundPool.load方法,返回的sampleId被保存在SOUND_EFFECT_FILES_MAP和poolId中
int sampleId = mSoundPool.load(filePath, 0);
if (sampleId <= 0) {
Log.w(TAG, "Soundpool could not load file: "+filePath);
} else {
SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
numSamples++;
}
} else {
SOUND_EFFECT_FILES_MAP[effect][1] =
poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
}
}
// wait for all samples to be loaded
if (numSamples > 0) {
mSoundPoolCallBack.setSamples(poolId);
attempts = 3;
status = 1;
while ((status == 1) && (attempts-- > 0)) {
try {
mSoundEffectsLock.wait(SOUND_EFFECTS_LOAD_TIMEOUT_MS);
status = mSoundPoolCallBack.status();
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted while waiting sound pool callback.");
}
}
} else {
status = -1;
}
if (mSoundPoolLooper != null) {
mSoundPoolLooper.quit();
mSoundPoolLooper = null;
}
mSoundPoolListenerThread = null;
if (status != 0) {
Log.w(TAG,
"onLoadSoundEffects(), Error "+status+ " while loading samples");
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
SOUND_EFFECT_FILES_MAP[effect][1] = -1;
}
}
mSoundPool.release();
mSoundPool = null;
}
}
return (status == 0);
}
private String getSoundEffectFilePath(int effectType) {
String filePath = Environment.getProductDirectory() + SOUND_EFFECTS_PATH
+ SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effectType][0]);
if (!new File(filePath).isFile()) {
filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH
+ SOUND_EFFECT_FILES.get(SOUND_EFFECT_FILES_MAP[effectType][0]);
}
Log.d(TAG, "SoundEffectFilePath is : "+filePath);
return filePath;
}
代碼中難懂的部分基本上都有註釋,核心其實就是爲SoundPool的load方法準備參數,其中有些數組嵌套的部分比較繞,但是隻要把數組都寫出來就一目瞭然了
onLoadSoundEffects基本上就是loadSoundEffects的全部內容,最後再來看一下onPlaySoundEffect的剩餘部分
private void onPlaySoundEffect(int effectType, int volume) {
synchronized (mSoundEffectsLock) {
onLoadSoundEffects();
if (mSoundPool == null) {
return;
}
float volFloat;
// use default if volume is not specified by caller
if (volume < 0) {
volFloat = (float)Math.pow(10, (float)sSoundEffectVolumeDb/20);
} else {
volFloat = volume / 1000.0f;
}
if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
//調用SoundPool的play方法
mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1],
volFloat, volFloat, 0, 0, 1.0f);
Log.w(TAG, "Touch tone played");
} else {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
String filePath = getSoundEffectFilePath(effectType);
mediaPlayer.setDataSource(filePath);
mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
mediaPlayer.prepare();
mediaPlayer.setVolume(volFloat);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
cleanupPlayer(mp);
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
cleanupPlayer(mp);
return true;
}
});
mediaPlayer.start();
} catch (IOException ex) {
Log.w(TAG, "MediaPlayer IOException: "+ex);
} catch (IllegalArgumentException ex) {
Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
} catch (IllegalStateException ex) {
Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
}
}
}
}
其中值得注意的點其實就只有SoundPool的play方法,其中傳入了音量大小和之前load返回的sampleId
二、替換原生按鍵音
摘要:替換原生按鍵音的主要思路是:在初始化的時候在相關數組中增加自己自定義的音頻資源,爲了達到這個目的需要在文件中增加一些代表自己文件資源的常量,具體在哪個文件中增加,其實完全可以在熟悉源碼流程之後模仿源碼來增加;之後在播放按鍵音的時候主動調用自己的按鍵音資源就可以了;最後當然別忘了把音頻文件push到設備中去。
需要修改的文件如下:
/frameworks/base/media/java/android/media/AudioManager.java
需要增加自己的音頻種類,起名爲:FX_KEYPRESS_CUSTOM,並把最大音頻數量修改爲11
/**
* Invalid keypress sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_INVALID = 9;
/**
* @hide Custom sound
* @see #playSoundEffect(int)
*/
public static final int FX_KEYPRESS_CUSTOM = 10;
/**
* @hide Number of sound effects
*/
public static final int NUM_SOUND_EFFECTS = 11;
需要注意的是自己增加的常量最好全部hide標記,這樣可以免去執行make update-api指令,同時並不會影響使用,之後的修改都會遵循這一原則
/frameworks/base/core/java/android/view/SoundEffectConstants.java
同樣需要增加一個常量:
public static final int CLICK = 0;
public static final int NAVIGATION_LEFT = 1;
public static final int NAVIGATION_UP = 2;
public static final int NAVIGATION_RIGHT = 3;
public static final int NAVIGATION_DOWN = 4;
/**
* @hide Custom click sound
*/
public static final int CLICK_CUSTOM = 5;
/frameworks/base/core/res/res/xml/audio_assets.xml
在XML文件中增加一個自己的音頻文件,注意id和之前在AudioManager.java中增加的常量一致,file和push到設備中的文件名保持一致
<audio_assets version="1.0">
<group name="touch_sounds">
<asset id="FX_KEY_CLICK" file="Effect_Tick.ogg"/>
<asset id="FX_FOCUS_NAVIGATION_UP" file="Effect_Tick.ogg"/>
<asset id="FX_FOCUS_NAVIGATION_DOWN" file="Effect_Tick.ogg"/>
<asset id="FX_FOCUS_NAVIGATION_LEFT" file="Effect_Tick.ogg"/>
<asset id="FX_FOCUS_NAVIGATION_RIGHT" file="Effect_Tick.ogg"/>
<asset id="FX_KEYPRESS_STANDARD" file="KeypressStandard.ogg"/>
<asset id="FX_KEYPRESS_SPACEBAR" file="KeypressSpacebar.ogg"/>
<asset id="FX_KEYPRESS_DELETE" file="KeypressDelete.ogg"/>
<asset id="FX_KEYPRESS_RETURN" file="KeypressReturn.ogg"/>
<asset id="FX_KEYPRESS_INVALID" file="KeypressInvalid.ogg"/>
<asset id="FX_KEYPRESS_CUSTOM" file="boom.ogg"/>
</group>
</audio_assets>
準備工作已經完成了,現在來修改一下調用流程,主動調用自己的按鍵音
/frameworks/base/core/java/android/view/View.java
調用playSoundEffect時傳入之前增加的常量:
public boolean performClick() {
// We still need to call this method to handle the cases where performClick() was called
// externally, instead of through performClickInternal()
notifyAutofillManagerOnClick();
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK_CUSTOM);//修改這裏
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
notifyEnterOrExitForAutoFillIfNeeded(true);
return result;
}
/frameworks/base/core/java/android/view/ViewRootImpl.java
View.java之後會調用到ViewRootImpl.java中,在switch/case中加入我們自己的情況:
@Override
public void playSoundEffect(int effectId) {
checkThread();
Log.d(mTag, "playSoundEffect");
try {
final AudioManager audioManager = getAudioManager();
switch (effectId) {
case SoundEffectConstants.CLICK:
audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
return;
case SoundEffectConstants.NAVIGATION_DOWN:
audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
return;
case SoundEffectConstants.NAVIGATION_LEFT:
audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
return;
case SoundEffectConstants.NAVIGATION_RIGHT:
audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
return;
case SoundEffectConstants.NAVIGATION_UP:
audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
return;
//增加的case語句
case SoundEffectConstants.CLICK_CUSTOM:
audioManager.playSoundEffect(AudioManager.FX_KEYPRESS_CUSTOM);
Log.d(mTag, "play my SoundEffect");
return;
default:
throw new IllegalArgumentException("unknown effect id " + effectId +
" not defined in " + SoundEffectConstants.class.getCanonicalName());
}
} catch (IllegalStateException e) {
// Exception thrown by getAudioManager() when mView is null
Log.e(mTag, "FATAL EXCEPTION when attempting to play sound effect: " + e);
e.printStackTrace();
}
}
以上就是修改的全部文件了,實際上只有5個文件,比預想的要簡單的多,這全都要歸功於Android源碼出色的設計模式使其在代碼上高度解耦
別忘了把音頻文件push到設備裏面,否則會啓動異常的哦!push的路徑爲:/system/media/audio/ui/
可能有些小夥伴對於爲什麼要修改上面的文件有一些疑問,這裏附上播放按鍵音的UML時序圖,只要熟悉調用流程,就明白了
三、調節按鍵音音量方法
其實在之前的講解過程中已經說到了,在調用SoundPool.play的時候其實會傳入左右聲道的音量值,只要按圖索驥找到之前是在哪裏傳入的音量就可以啦!其實是在playSoundEffectVolume方法傳入的音量值,那麼只要在這個方法的參數中傳入你想要的值就行了。