【问题标题】:How do I get the device audio level in percentage on Android?如何在 Android 上以百分比形式获取设备音频级别?
【发布时间】:2017-08-09 21:45:13
【问题描述】:

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

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

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

【问题讨论】:

标签: android device volume


【解决方案1】:
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 将是您的百分比!

【讨论】:

  • 我认为您在使用整数除法时是偶然的。应该是int currentVolumePercentage = 100.0 * currentVolume/maxVolume;
  • 评估顺序是从左到右。所以双常数应该在左边。否则,当“损坏”已经完成时,您只是将整数除法结果相乘。 docs.oracle.com/javase/specs/jls/se7/html/jls-15.html 点赞赞赏。 :-)
【解决方案2】:

在 kotlin 函数中的相同 Trenton Telge 答案

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
}

【讨论】:

    猜你喜欢
    • 2023-02-24
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多