Android调试 USB音量范围修改

参考博文:《Android原生音量控制》

参考博文:《深入理解AudioService》

一、问题描述

不连接USB耳机时,系统音量可以设置到最大值15,连接USB耳机后,系统音量仅能设置到4

一、原因分析

(1)安卓音频系统对不同的音频流设置了不同的音量控制范围,推测与该范围设置有关

Android调试 USB音量范围修改_第1张图片

但是在源码中STREAM_MUSIC的最大值已经设置为了15,  mSafeMediaVolumeState  = 10,安全音量也已经设置为了10

安全音量在xml文件中配置

//AudioService.java  
      mSafeMediaVolumeState = new Integer(Settings.Global.getInt(mContentResolver,
                                                        Settings.Global.AUDIO_SAFE_VOLUME_STATE,
                                                        SAFE_MEDIA_VOLUME_NOT_CONFIGURED));


///////line284

 /** Maximum volume index values for audio streams */
    private static int[] MAX_STREAM_VOLUME = new int[] {
        5,  // STREAM_VOICE_CALL
        7,  // STREAM_SYSTEM
        7,  // STREAM_RING
        15, // STREAM_MUSIC
        7,  // STREAM_ALARM
        7,  // STREAM_NOTIFICATION
        15, // STREAM_BLUETOOTH_SCO
        7,  // STREAM_SYSTEM_ENFORCED
        15, // STREAM_DTMF
        15, // STREAM_TTS
        15  // STREAM_ACCESSIBILITY
    };


(2)USB音频的音量设置

可以看到USB音频根据MUSIC的音量计算出来

//AudioService.java 6208 
private int safeMediaVolumeIndex(int device) {
        if ((device & mSafeMediaVolumeDevices) == 0) {
			Slog.w(TAG,"SOLEN return MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]");
            return MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC];
        }
        if (device == AudioSystem.DEVICE_OUT_USB_HEADSET) {
			Slog.w(TAG,"SOLEN mSafeUsbMediaVolumeIndex" + Integer.toHexString(mSafeUsbMediaVolumeIndex));
            return mSafeUsbMediaVolumeIndex;
        } else {
            return mSafeMediaVolumeIndex;
        }
    }




//AudioService.java 754
        // relies on audio policy having correct ranges for volume indexes.
        mSafeUsbMediaVolumeIndex = getSafeUsbMediaVolumeIndex();


    private int getSafeUsbMediaVolumeIndex()
    {
        // determine UI volume index corresponding to the wanted safe gain in dBFS
        int min = MIN_STREAM_VOLUME[AudioSystem.STREAM_MUSIC];
        int max = MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC];

        while (Math.abs(max-min) > 1) {
            int index = (max + min) / 2;
            float gainDB = AudioSystem.getStreamVolumeDB(
                    AudioSystem.STREAM_MUSIC, index, AudioSystem.DEVICE_OUT_USB_HEADSET);
            if (Float.isNaN(gainDB)) {
                //keep last min in case of read error
                break;
            } else if (gainDB == SAFE_VOLUME_GAIN_DBFS) {
                min = index;
                break;
            } else if (gainDB < SAFE_VOLUME_GAIN_DBFS) {
                min = index;
            } else {
                max = index;
            }
        }
        return min * 10;
    

直接修改mSafeUsbMediaVolumeIndex的值为150,问题解决。安卓音频系统加了一个精度设计,将音量都X10处理了,150实际上就是15,音量的最大值。

 

 

 

 

你可能感兴趣的:(Android,SDK)