改变系统的音量,除非涉及到管理各种音量的工具类软件,一般是改变媒体音量,也就是
AudioManager.STREAM_MUSIC,比如说打游戏的时候,不能把电话的音量改变了。这样的话需要用到
设置当前音量
监听音量键事件
private AudioManager audioMgr;
audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
获取最大音量
maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
不同手机的系统最大音量不一样,所以如果需要显示音量变化,需要自己分等份获取当前音量
private int getMediaVolume() {
return audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC);
}
设置当前音量
private void setMediaVolume(int volume) {
audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_PLAY_SOUND);
}
监听音量键事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
addMediaVolume(getMediaVolume());
playMedia(getMediaVolume());
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
cutMediaVolume(getMediaVolume());
playMedia(getMediaVolume());
return true;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
private void addMediaVolume(int current) {
current = current + stepVolume;
if (current >= maxVolume)
current = maxVolume;
setMediaVolume(current);
volumeSeekBar.setProgress(current);
}
private void cutMediaVolume(int current) {
current = current - stepVolume;
if (current <= 0)
current = 0;
setMediaVolume(current);
volumeSeekBar.setProgress(current);
}
播放
private void playMedia(int volume) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
return;
}
int music = volumeManager.getMusic();
if (music != mMusic) {
mediaPlayer = MediaPlayer.create(getApplicationContext(), music);
mMusic = music;
}
mediaPlayer.start();
}