最近在做Android Audio方面的工作,有需求是在调节Volume_Up_Key & Volume_Down_key时,Spearker or Headset每音阶的衰减变为3db左右。所以利用Source Insight分析Android源码中音量控制的流程,如有错误,欢迎指正,谢谢!  

  以下是调节音量的流程:

  Step_1.首先在调节机台Volume_Up_Key & Volume_Down_Key操作时,系统会调用到AudioManager.java中handleKeyUp & handleKeyDown函数,以 handleKeyDown函数为例:

 public void handleKeyDown(KeyEvent event, int stream) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: /*KeyEvent 在KeyEvent.java中定义*/
case KeyEvent.KEYCODE_VOLUME_DOWN: int flags = FLAG_SHOW_UI | FLAG_VIBRATE; if (mUseMasterVolume) {
adjustMasterVolume(
keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_RAISE
: ADJUST_LOWER,
flags);
} else {
adjustSuggestedStreamVolume(
keyCode == KeyEvent.KEYCODE_VOLUME_UP
? ADJUST_RAISE
: ADJUST_LOWER,
stream,
flags);
}
break;
       ... ...
}
}

  其中是否进入adjustMasterVolume 函数是通过mUseMasterVolume的值判断的,而mUseMasterVolume的值是在AudioManager的构造函数中定义,其值的大小如下:mUseMasterVolume = mContext.getResources().getBoolean(com.android.internal.R.bool.config_useMasterVolume),所以首先从系统的配置文件config.xml中查找config_useMasterVolume值的大小

  <bool name="config_useMasterVolume">false</bool>

  所以handleKeyDown中 switch语句中会选择进入adjustSuggestedStreamVolume函数。

     public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
IAudioService service = getService();
try {
if (mUseMasterVolume) {
service.adjustMasterVolume(direction, flags, mContext.getOpPackageName());
} else {
service.adjustSuggestedStreamVolume(direction, suggestedStreamType, flags,
mContext.getOpPackageName());
}
  ... ...
      }
}

  Step_2.在adjustSuggestedStreamVolume函数中首先会通过binder机制得到AudioService,并将音量控制过程转入到AudioService.java中。

     public void adjustStreamVolume(int streamType, int direction, int flags,
String callingPackage) {
... ...
/*音量调大时,若要超过SafeMediaVolume时,系统会弹出对话框给予确认*/
if ((direction == AudioManager.ADJUST_RAISE) &&
!checkSafeMediaVolume(streamTypeAlias, aliasIndex + step, device)) {
Log.e(TAG, "adjustStreamVolume() safe volume index = "+oldIndex);
mVolumePanel.postDisplaySafeVolumeWarning(flags);
} else if (streamState.adjustIndex(direction * step, device)) {
sendMsg(mAudioHandler,
MSG_SET_DEVICE_VOLUME, /*需要处理的Message值*/
SENDMSG_QUEUE,
device,
0,
streamState,
0);
}
}
int index = mStreamStates[streamType].getIndex(device);
sendVolumeUpdate(streamType, oldIndex, index, flags); /*通知上层更新Volume*/
}

  在adjustStreamVolume 中会通过sendMsg的方式来将调节音量的事件加入到消息列队SENDMSG_QUENE中,当轮寻到该Message时,系统会调用handleMessage函数来处理该Message,此时该处对应的Message为MSG_SET_DEVICE_VOLUME。

        public void handleMessage(Message msg) {

             switch (msg.what) {

                 case MSG_SET_DEVICE_VOLUME:
setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
break; case MSG_SET_ALL_VOLUMES:
setAllVolumes((VolumeStreamState) msg.obj);
break;   ... ...
}
}

  可以发现当msg.what =  MSG_SET_DEVICE_VOLUME时,会进到setDeviceVolume函数中,继续往下分析:

         private void setDeviceVolume(VolumeStreamState streamState, int device) {

             // Apply volume
streamState.applyDeviceVolume(device); // Apply change to all streams using this one as alias
     ... ... // Post a persist volume msg
     ... ...
}

  applyDeviceVolume就是将音量Volume设置到对应的设备Device上,继续往下分析:

         public void applyDeviceVolume(int device) {
int index;
if (isMuted()) {
index = 0;
} else if ((device & AudioSystem.DEVICE_OUT_ALL_A2DP) != 0 &&
mAvrcpAbsVolSupported) {
index = (mIndexMax + 5)/10;
} else {
index = (getIndex(device) + 5)/10;
}
AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
}

  此处VolumeIndex就是对应UI界面调节音量时,音量所处在的位置下标。在AudioService.java中定义了每种音频流对应的Max-Index,在AudioManager.java中定义了每种音频流在第一次刷机后默认的Index。

  Step_3.此时得到音量的下标Index后,会调用AudioSystem.java中的setStreamVolumeIndex函数中来得到此时音量的放大倍数。通过JNI层调用到AudioSystem.cpp文件中的 setStreamVolumeIndex中。

 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
int index,
audio_devices_t device)
{
const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
if (aps == ) return PERMISSION_DENIED;
return aps->setStreamVolumeIndex(stream, index, device);
}

  setStreamVolumeIndex函数中比较简单,通过StrongPointer来与AudioPolicyService建立联系,将AudioSystem中的setStreamVolumeIndex操作移到aps中完成。下面进入到AudioPolicyService.cpp文件中的setStreamVolumeIndex继续分析:

 status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
int index,
audio_devices_t device)
{
... ...
if (mpAudioPolicy->set_stream_volume_index_for_device) {
return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,
stream,
index,
device);
} else {
return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
}
}

  Step_4.AudioPolicyService.cpp作为bn端,其对应的bp端为AudioPolicyManagerBase.cpp。在当前函数的if语句中判断AudioPolicyManagerBase.cpp文件中是否存在setStreamVolumeIndexForDevice函数,条件成立则会选择setStreamVolumeIndexForDevice作为函数入口端;否则选择setStreamVolumeIndex作为函数入口。现在进入AudioPolicyManagerBase.cpp中文件中完成最后的分析:

 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
int index,
audio_devices_t device)
{
... ...
// compute and apply stream volume on all outputs according to connected device
status_t status = NO_ERROR;
for (size_t i = ; i < mOutputs.size(); i++) {
audio_devices_t curDevice =
getDeviceForVolume(mOutputs.valueAt(i)->device());
if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
if (volStatus != NO_ERROR) {
status = volStatus;
}
}
}
return status;
}

继续调用checkAndSetVolume函数:

 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
int index,
audio_io_handle_t output,
audio_devices_t device,
int delayMs,
bool force)
{ // do not change actual stream volume if the stream is muted
... ...
// do not change in call volume if bluetooth is connected and vice versa
... ...
audio_devices_t checkedDevice = (device == AUDIO_DEVICE_NONE) ? mOutputs.valueFor(output)->device() : device;
float volume = computeVolume(stream, index, checkedDevice); ... ...
  mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);/*将得到的volume应用到对应的output中*/
}

  在checkAndSetVolume中可以知道volume是通过computeVolume得到的。继续向下分析:

float AudioPolicyManagerBase::computeVolume(int stream,
int index,
audio_devices_t device)
{
... ...
volume = volIndexToAmpl(device, streamDesc, index);
... ...
return volume;
}

  终于到了最后volIndexToAmpl,从函数名就可以知道该函数的作用是通过volIndex得到音量放大倍数。

float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
int indexInUi)
{
device_category deviceCategory = getDeviceCategory(device);
const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory]; // the volume index in the UI is relative to the min and max volume indices for this stream type
int nbSteps = + curve[VOLMAX].mIndex -
curve[VOLMIN].mIndex;
int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
(streamDesc.mIndexMax - streamDesc.mIndexMin); // find what part of the curve this index volume belongs to, or if it's out of bounds
int segment = ;
if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
return 0.0f;
} else if (volIdx < curve[VOLKNEE1].mIndex) {
segment = ;
} else if (volIdx < curve[VOLKNEE2].mIndex) {
segment = ;
} else if (volIdx <= curve[VOLMAX].mIndex) {
segment = ;
} else { // out of bounds
return 1.0f;
} // linear interpolation in the attenuation table in dB
float decibels = curve[segment].mDBAttenuation +
((float)(volIdx - curve[segment].mIndex)) *
( (curve[segment+].mDBAttenuation -
curve[segment].mDBAttenuation) /
((float)(curve[segment+].mIndex -
curve[segment].mIndex)) ); float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 ) return amplification;
}

  其中curve代表在用设备(如SPEAKER、HEADSET & EARPIECE)播放音频流(如SYSTEM、MUSIC、ALARM、RING & TTS等)时的音量曲线,最后decibles & amplification就是我们需要求的值,其中decibles代表某一音节所对应的dB值,而amplification则是由dB值转化得到的音量放大倍数。这样整个音量调节过程到此就算完成了,具体的计算分析会放在后面继续分析。

  

最新文章

  1. web自动化工具-livereload
  2. asp.net mvc 表单相关
  3. applet示例 WelcomeApplet.java &lt;Core Java&gt;
  4. SharePoint 2013 搜索爬网功能
  5. KMP的原理详细讲解
  6. [Unity菜鸟] Character控制移动
  7. selenium webdriver(3)---操作页面对象
  8. ASP.NET母版与内容页相对路径的问题
  9. JS 工具 构建工具
  10. codeforces 630C - Lucky Numbers 递推思路
  11. 连接HTTP服务器
  12. .NET Core微服务之路:基于gRPC服务发现与服务治理的方案
  13. 构造函数,C++内存管理,内存泄漏定位
  14. python实现排序算法四:BFPTR算法
  15. SqlServer 一个查询语句导致tempdb增大55G(转载)
  16. Android创建并响应选项菜单
  17. Android RxJava+Retrofit完美封装
  18. K8S从私有仓库拉取镜像
  19. CentOS7.5之Sqoop1.4.7的安装使用
  20. 机器学习(5): K-means 算法

热门文章

  1. 上传Docker镜像到阿里云
  2. AWS系列-S3实现文件服务页面展示
  3. 关于Bootstrap的理解
  4. 编程之美 set 5 寻找数组中最大值和最小值
  5. 编写jsp动态网页
  6. input的disable和readonly
  7. python3 + selenium + (chrome and firefox)使用
  8. Python--进阶处理5
  9. java讲讲几种常见的排序算法(二)
  10. c#使用FastReports打印