作为一名Android开发人员,对源码的阅读是必不可少的。但是Android源码那么庞大,从何开始阅读,如何开始阅读,很多人都会感觉无从下手,今天我来带着问题,去带大家分析一下Android源码,并解决问题。源码并不可怕,耐着性子看就好了。
今天我们来看一下如何增大按键音量呢,下面贴一下调用播放按键音方法的代码:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.playSoundEffect(3);
了解Audio服务和Binder机制的朋友肯定都知道,这个AudioManager是什么。我们这边获取的audioManager其实就是Android系统在系统启动时,注册的系统服务AudioService的代理对象的包装,我们可以这么理解。如果有朋友对Binder机制不了解的,可以去网上搜搜其他文章。
在这里,我们调用audioManager的playSoundEffect进行按键音的播放。
下面我们一步步跟下去,看看这个playSoundEffect方法到底做了什么事。
1.AudioManager.playSoundEffect
public void playSoundEffect(int effectType) {
if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
return;
}
if (!querySoundEffectsEnabled(Process.myUserHandle().getIdentifier())) {
return;
}
final IAudioService service = getService();
try {
//调用AudioService的playSoundEffect方法,跨进程调用
//这个service其实就是AudioService在java端的代理对象
service.playSoundEffect(effectType);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
2.AudioService.playSoundEffect
/** @see AudioManager#playSoundEffect(int) */
public void playSoundEffect(int effectType) {
//第二个参数代表软件音量,可以由调用者传入,我们今天说的调节音量的大小说的不是这个
playSoundEffectVolume(effectType, -1.0f);
}
/** @see AudioManager#playSoundEffect(int, float) */
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);
}
playSoundEffect方法最终走到了playSoundEffectVolume,并且调用sendMsg发送了一个消息。
3. onPlaySoundEffect(msg.arg1, msg.arg2);
mAudioHandler在处理MSG_PLAY_SOUND_EFFECT这个消息时,调用了onPlaySoundEffect这个方法,这个方法主要做了什么事呢,我们继续往下看。
private void onPlaySoundEffect(int effectType, int volume) {
synchronized (mSoundEffectsLock) {
//1.初始化资源
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播放
mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1],
volFloat, volFloat, 0, 0, 1.0f);
} else {
//MediaPlayer播放
MediaPlayer mediaPlayer = new MediaPlayer();
try {
String filePath = getSoundEffectFilePath(effectType);
mediaPlayer.setDataSource(filePath);
mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
mediaPlayer.prepare();
mediaP

最低0.47元/天 解锁文章
534

被折叠的 条评论
为什么被折叠?



