播放音樂類軟體,使用者在調節音量的時候,彈出系統的媒體音量介面,與項目的設計風格格格不入。
於是,調節音量,同時顯示自己定義的媒體音量介面很有必要。
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);
}
得到當前音量和最大音量,可以繪製和自己應用風格一致的媒體音量介面了。