播放音乐类软件,用户在调节音量的时候,弹出系统的媒体音量界面,与项目的设计风格格格不入。
于是,调节音量,同时显示自己定义的媒体音量界面很有必要。
1)调整音乐音量
private AudioManager audioManager = null; // 音频
audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
增加减少音量:
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND
| AudioManager.FLAG_SHOW_UI);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND
| AudioManager.FLAG_SHOW_UI);
AudioManager.FLAG_SHOW_UI即显示了媒体音量界面,去掉即可隐藏。重写onKeyDown方法:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
return true;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
同时显示自己定义的媒体音量界面即可。
2)自定义媒体音量界面
需要获取当前音量。方法如下:
private void GetV() {
// 通话音量
int max = audioManager
.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
int current = audioManager
.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
Log.d("VIOCE_CALL", "max : " + max + " current : " + current);
// 系统音量
max = audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
current = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
Log.d("SYSTEM", "max : " + max + " current : " + current);
// 铃声音量
max = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
current = audioManager.getStreamVolume(AudioManager.STREAM_RING);
Log.d("RING", "max : " + max + " current : " + current);
// 音乐音量
max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.d("MUSIC", "max : " + max + " current : " + current);
// 提示声音音量
max = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
current = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
Log.d("ALARM", "max : " + max + " current : " + current);
}
得到当前音量和最大音量,可以绘制和自己应用风格一致的媒体音量界面了。