如何在 Android 上获取设备音频电平的百分比?

How do I get the device audio level in percentage on Android?

我正在尝试让我的 android 应用程序检查设备的音量(媒体,而不是铃声)是否低于 'x'%,但我不确定如何。我目前正在尝试这个:

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume <0.7) {message};

编辑:我想要音量的百分比,比如10%/20%...

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int currentVolumePercentage = 100 * currentVolume/maxVolume;   

currentVolumePercentage 将是你的百分比!

kotlin 函数中的相同 答案

fun getCurrentAudioLevelPercentage(context: Context): Int {
    val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
    val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    val percentage = 100 * currentVolume / maxVolume
    return percentage
}