Android - 声音渐变

主要思路
  • 1.问题:在多媒体应用开发中,暂停播放按钮切换时,如果声音音量之间变化过大,会出现声音卡一下或者出现杂音等问题。
  • 2.暂停 -> 播放:获取当前音量值,按照一定混音比例和时间差,进行声音提高渐变。
  • 3.播放 -> 暂停:获取当前音量值,按照一定混音比例和时间差,进行声音压低渐变。
1.声音抬高渐变
 private void releaseVolumeForNavi() {
    mTargetVolume = MAX_VOLUME_STREAM_MUSIC;
    mHandler.removeMessages(MSG_COMMAND_FADEUP);   
    mHandler.sendEmptyMessage(MSG_COMMAND_FADEDOWN);
    mHandler.removeMessages(MSG_COMMAND_FADEUP);
}

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
        case MSG_COMMAND_FADEDOWN:
            if(mTargetVolume == getVolume(false)) {
                return;
            }
            
            if(mCurrentVolume > 0 && mCurrentVolume > mTargetVolume) {
                mCurrentVolume --;
                setMusicStreamVolume(mCurrentVolume);
                mHandler.sendEmptyMessageDelayed(MSG_COMMAND_FADEDOWN, 14);
            }
            break;
        case MSG_COMMAND_FADEUP:
            mTargetVolume = getVolume(false);
            if(mCurrentVolume < mTargetVolume) {
                mCurrentVolume ++;
                setMusicStreamVolume(mCurrentVolume);
                mHandler.sendEmptyMessageDelayed(MSG_COMMAND_FADEUP, 14);
            } else {
                mCurrentVolume = 0;
            }
            break;
        }
    };
};

private int getVolume(boolean isBtVol) {
    return mAudioManager.getStreamVolume(isBtVol?AudioManager.STREAM_VOICE_CALL:AudioManager.STREAM_MUSIC);
}

private void setMusicStreamVolume(int vol) {
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, FLAG_UPDATE_VOLUME_BYPASS);
}
2.声音压低渐变
public void focusVolumeForNavi() {
    int volumeNavi = Settings.System.getInt(getContentResolver(), "navi_volume",7);//默认混音比例为7 (根据效果自己设置)
    int maxMusicIndex = MAX_VOLUME_STREAM_MUSIC;
    int focusIndex = 0;
    if(volumeNavi == 0) {
        focusIndex = 0;
    } else if (volumeNavi == MAX_VOLUME_NAVI) {
        focusIndex = maxMusicIndex;
    } else {
        float percent = (float) volumeNavi / (float)maxMusicIndex;
        focusIndex = (int)(maxMusicIndex * percent);
    }
    mTargetVolume = focusIndex;
    mHandler.removeMessages(MSG_COMMAND_FADEDOWN);
    mHandler.removeMessages(MSG_COMMAND_FADEUP);
    mHandler.sendEmptyMessage(MSG_COMMAND_FADEDOWN);
    
}
3.相关变量声明
private static final int MSG_COMMAND_FADEDOWN = 0x1204;
private static final int MSG_COMMAND_FADEUP = 0x1205;
private final int MAX_VOLUME_NAVI = 15;
private int MAX_VOLUME_STREAM_MUSIC = 26;
private int mTargetVolume;
private int mCurrentVolume = 0;

private AudioManager mAudioManager;
int FLAG_UPDATE_VOLUME_BYPASS = 1 << 17;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    MAX_VOLUME_STREAM_MUSIC = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}

你可能感兴趣的:(Android - 声音渐变)