對於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進行設置音量。