Android系统音量调节机制执行过程
前言
做有关APK项目时用到了Android系统的音量调节相关的知识,于是去追了Android源码,下面来简单介绍下。
正文
在APP层调用的代码如下:
private AudioManager audioManager;
int index = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int device = AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
double decible = (double)audioManager.getStreamVolumeDb(AudioManager.STREAM_MUCIC, index, device);
AudioManager.java文件在Framework层,部分代码如下:
public float getStreamVolumeDb(@PublicStreamTypes int streamType, int index,
@AudioDeviceInfo.AudioDeviceTypeOut int deviceType)
{
if (!isPublicStreamType(streamType)) {
throw new IllegalArgumentException("Invalid stream type " + streamType);
}
if (index > getStreamMaxVolume(streamType) || index < getStreamMinVolume(streamType)) {
throw new IllegalArgumentException("Invalid stream volume index " + index);
}
if (!AudioDeviceInfo.isValidAudioDeviceTypeOut(deviceType)) {
throw new IllegalArgumentException("Invalid audio output device type " + deviceType);
}
final float gain = AudioSystem.getStreamVolumeDB(streamType, index, AudioDeviceInfo.convertDeviceTypeToInternalDevice(deviceType));//此函数在AudioSystem.java
if (gain <= VOLUME_MIN_DB) {
return Float.NEGATIVE_INFINITY;
} else {
return gain;
}
}
AudioSystem.java文件在Framework层,部分代码如下:
public static native float getStreamVolumeDB(int stream, int index, int device);//调用AudioPolicyManager类的getStreamVolumeDB方法
AudioPolicyManager.cpp类在Native层,部分代码如下:
float AudioPolicyManager::getStreamVolumeDB(audio_stream_type_t stream,
int index, audio_devices_t device)
{
return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {
device});
}
...
float AudioPolicyManager::computeVolume(IVolumeCurves &cu