Android中絕對音量和相對音量設置

前言:

絕對音量: 手機端不處理音量,隻把當前音量告訴耳機,耳機端處理音量。

相對音量: 手機端處理,耳機端不確定是默認最大,還是有一個默認音量還是按照之前設置的絕對音量的值處理的。

手機音量轉換絕對音量,此處會有一個計算過程,大致就是手機側計算出當前音量和最大音量的百分比然後設置給耳機,耳機端收到百分比去處理。不然每個手機的音量范圍不同,不做歸一化就很難適配。

當通過音量按鍵調節音量時,會通過input事件分發,input把event分發給mediassesion, mediasession調用audiomanager的adjustStreamVolume調節音量。

當通過拖動音量條調節音量時,settings app會調用audiomanager的setStreamVolume調節音量。

adjustStreamVolume和setStreamVolume處理過程類似,接下來隻看setStreamVolume。

setStreamVolume調用

// frameworks/base/media/java/android/media/AudioManager.java
public void setStreamVolume(int streamType, int index, int flags) {
    final IAudioService service = getService();
    try {
        service.setStreamVolume(streamType, index, flags, getContext().getOpPackageName()); // audiomanager調用的是audioservice的setStreamVolume
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

audioservice的調用過程:

// frameworks/base/services/core/java/com/android/server/audio/AudioService.java
private void setStreamVolume(int streamType, int index, int flags, String callingPackage, String caller, int uid, boolean hasModifyAudioSettings) {
    ensureValidStreamType(streamType);
    int streamTypeAlias = mStreamVolumeAlias[streamType];
    VolumeStreamState streamState = mStreamStates[streamTypeAlias];
    inal int device = getDeviceForStream(streamType); // 獲取streamType對應的device
    int oldIndex;
 
     synchronized (mSafeMediaVolumeStateLock) {
        // reset any pending volume command
        mPendingVolumeCommand = null;
        oldIndex = streamState.getIndex(device);
        android.media.AudioServiceInjector.mOriginalIndexWhenSetStreamVolume = index;
        index = rescaleIndex(index * 10, streamType, streamTypeAlias);
 
        // 設置絕對音量
        if (streamTypeAlias == AudioSystem.STREAM_MUSIC && AudioSystem.DEVICE_OUT_ALL_A2DP_SET.contains(device) && (flags & AudioManager.FLAG_BLUETOOTH_ABS_VOLUME) == 0) {
            mDeviceBroker.postSetAvrcpAbsoluteVolumeIndex(index / 10);
        }
 
        if (streamTypeAlias == AudioSystem.STREAM_MUSIC) {
            setSystemAudioVolume(oldIndex, index, getStreamMaxVolume(streamType), flags); // 這裡是和hdmi相關,不用管
        }
 
        flags &= ~AudioManager.FLAG_FIXED_VOLUME;
        if (streamTypeAlias == AudioSystem.STREAM_MUSIC && isFixedVolumeDevice(device)) {
            flags |= AudioManager.FLAG_FIXED_VOLUME;
 
            // volume is either 0 or max allowed for fixed volume devices
            if (index != 0) {
                if (mSafeMediaVolumeState == SAFE_MEDIA_VOLUME_ACTIVE && mSafeMediaVolumeDevices.contains(device)) {
                   index = safeMediaVolumeIndex(device);
                } else {
                   index = streamState.getMaxIndex();
                }
            }
        }
 
        if (!checkSafeMediaVolume(streamTypeAlias, index, device)) {
            mVolumeController.postDisplaySafeVolumeWarning(flags); // 這裡應該就是安全提醒,比如音量過大損傷聽力的提醒
            mPendingVolumeCommand = new StreamVolumeCommand(streamType, index, flags, device);
        } else {
            onSetStreamVolume(streamType, index, flags, device, caller, hasModifyAudioSettings); // 調用onSetStreamVolume設置音量
            index = mStreamStates[streamType].getIndex(device);
        }
    }
    sendVolumeUpdate(streamType, oldIndex, index, flags, device);
 }

onSetStreamVolume 和 sendVolumeUpdate的作用:

onSetStreamVolume -> 設置音量到底層並處理一些靜音邏輯。

sendVolumeUpdate -> 通知ui更新音量值

這裡插入個當音量設置到0時自動靜音的處理:

// frameworks/base/services/core/java/com/android/server/audio/AudioService.java
private void onSetStreamVolume(int streamType, int index, int flags, int device, String caller, boolean hasModifyAudioSettings) {
    final int stream = mStreamVolumeAlias[streamType];
    setStreamVolumeInt(stream, index, device, false, caller, hasModifyAudioSettings); // 設置音量到底層
    // setting volume on ui sounds stream type also controls silent mode
    if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || (stream == getUiSoundsStreamType())) {
       int ringerMode = getNewRingerMode(stream, index, flags); // 獲取ringmode
        miuiRingerMode = miui.util.AudioManagerHelper.getValidatedRingerMode(mContext, miuiRingerMode); // 獲取ringmode
        setRingerMode(ringerMode, TAG + ".onSetStreamVolume", false /*external*/); // 設置ringmode
    }
}
    
private int getNewRingerMode(int stream, int index, int flags) {
    if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || (stream == getUiSoundsStreamType())) {
        int newRingerMode;
        if (index == 0) { // 如果設置的音量是0
        // 如果有震動就設置ringmode是震動模式,否則判斷volumeDownToEnterSilent決定設置靜音還是不靜音
            newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE : mVolumePolicy.volumeDownToEnterSilent ? AudioManager.RINGER_MODE_SILENT : AudioManager.RINGER_MODE_NORMAL;
        } else {
            newRingerMode = AudioManager.RINGER_MODE_NORMAL; // 如果音量不是0,ringmode設置為非靜音
        }
        return newRingerMode;
    }
    return getRingerModeExternal();
}

設置絕對音量: postSetAvrcpAbsoluteVolumeIndex

// frameworks/base/services/core/java/com/android/server/audio/AudioDeviceBroker.java
void postSetAvrcpAbsoluteVolumeIndex(int index) {
    sendIMsgNoDelay(MSG_I_SET_AVRCP_ABSOLUTE_VOLUME, SENDMSG_REPLACE, index);
}
 
// 收到消息MSG_I_SET_AVRCP_ABSOLUTE_VOLUME,調用mBtHelper.setAvrcpAbsoluteVolumeIndex(msg.arg1);
 
// frameworks/base/services/core/java/com/android/server/audio/BtHelper.java
synchronized void setAvrcpAbsoluteVolumeIndex(int index) {
    mA2dp.setAvrcpAbsoluteVolume(index);
}

藍牙側絕對音量處理:

// vendor/qcom/opensource/commonsys/packages/apps/Bluetooth/src/com/android/bluetooth/a2dp/A2dpService.java
public void setAvrcpAbsoluteVolume(int volume) {
    if (mFactory.getAvrcpTargetService() != null) {
        mFactory.getAvrcpTargetService().sendVolumeChanged(volume);
        return;
    }
    if(ApmConstIntf.getLeAudioEnabled()) {
        VolumeManagerIntf mVolumeManager = VolumeManagerIntf.get();
        mVolumeManager.setMediaAbsoluteVolume(volume);
        return;
    }
    synchronized(mBtAvrcpLock) {
        if (mAvrcp_ext != null) {
           mAvrcp_ext.setAbsoluteVolume(volume);
           return;
        }
        if (mAvrcp != null) {
           mAvrcp.setAbsoluteVolume(volume);
        }
    }
}
 
// vendor/qcom/opensource/commonsys/bluetooth_ext/packages_apps_bluetooth_ext/src/avrcp/Avrcp_ext.java
public void setAbsoluteVolume(int volume) {
    Message msg = mHandler.obtainMessage(MSG_SET_ABSOLUTE_VOLUME, volume, 0);
    mHandler.sendMessage(msg);
}
 
收到消息MSG_SET_ABSOLUTE_VOLUME之後調用如下
case MSG_SET_ABSOLUTE_VOLUME: {
    int avrcpVolume = convertToAvrcpVolume(msg.arg1);
    ......
}
 
// 計算avrcpVolume
private int convertToAvrcpVolume(int volume) {
   if(mAudioStreamMax == 150) {
       return (int) Math.round((double) volume*AVRCP_MAX_VOL/mAudioStreamMax);
   }
   return (int) Math.ceil((double) volume*AVRCP_MAX_VOL/mAudioStreamMax);
}

從這裡可以看到,藍牙側傳給耳機的音量其實就是百分比。

從相對音量切換到絕對音量的處理:

藍牙APP有一個NotificationReceiver,當絕對音量的開關發生變化NotificationReceiver就會收到信息,然後做如下處理:

private class NotificationReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if(ABS_VOLUME_ACTION.equals(intent.getAction())) {
            handleDeviceAbsVolume(mac, value);
        }
    }
}
// handleDeviceAbsVolume就會做對應的處理,把音量值發送給耳機側。

此處每次切換的時候會有log打印,log mask: handleDeviceAbsVolume|setVolumeNative

切換之後播放聲音就會調用checkAndSetVolume把音量值設置到最大,保證手機側無音量處理。

從絕對音量切換到相對音量的處理:

和上面一樣,藍牙APP NotificationReceiver會收到絕對音量開關關閉的消息,然後把消息發給耳機端。然後還會調用audio側設置stream的音量。

log mask: handleDeviceAbsVolume|setStreamVolume

切換之後播放聲音就會調用checkAndSetVolume把音量值設置到當前實際的音量值。

總結

到此這篇關於Android中絕對音量和相對音量設置的文章就介紹到這瞭,更多相關Android音量設置內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: