Android 音量调节

时间:2023-03-09 14:57:33
Android 音量调节

对于Android的音量调节,可以分为按键调节音量和设置中调节音量。我们首先说一说设置中的音量调节。

一、音量的分类:

1.AudioManager.STREAM_VOICE_CALL

2.AudioManager.STREAM_RING

3.AudioManager.STREAM_MUSIC,

4.AudioManager.STREAM_ALARM

5.AudioManager.STREAM_NOTIFICATION

二、音量的范围:

对于不同类型的音量Android规定了不同的范围,在AudioService中有一个数组,定义了不同音量的范围。

private final 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
};

三:调节音量的方法:

int streamValue = am.getStreamVolume(streamType); 获取当前类型的音量值

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 获取音频服务

audioManager.setStreamVolume(mStreamType, streamValue, 0);  设置音量

现在说一下使用按键调节音量

使用按键调节音量,首先会在PhoneWinManager中收到一个按键的事件,然后调用AudioService中的adjustStreamVolume方法,源码如下:

/**
* Tell the audio service to adjust the volume appropriate to the event.
* @param keycode
*/
void handleVolumeKey(int stream, int keycode) {
IAudioService audioService = getAudioService();
if (audioService == null) {
return;
}
try {
// since audio is playing, we shouldn't have to hold a wake lock
// during the call, but we do it as a precaution for the rare possibility
// that the music stops right before we call this
// TODO: Actually handle MUTE.
mBroadcastWakeLock.acquire();
audioService.adjustStreamVolume(stream,
keycode == KeyEvent.KEYCODE_VOLUME_UP
? AudioManager.ADJUST_RAISE
: AudioManager.ADJUST_LOWER,
0);
} catch (RemoteException e) {
Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
} finally {
mBroadcastWakeLock.release();
}
}

在adjustStreamVolume会启动VolumePanel,也就是我们按音量键出现的界面。在VolumePanel中会调用AudioManager的setStreamVolume进行设置音量。