Android : How to set MediaPlayer volume programmatically?
如何以编程方式设置媒体播放器音量。我将它用于警报通知。任何帮助都非常感谢,并提前感谢。
使用 AudioManager,您可以简单地控制媒体播放器的音量。
1
2 |
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0); |
也来自 MediaPlayer(但我没有尝试过)
1
|
setVolume(float leftVolume, float rightVolume)
|
Since: API Level 1
Sets the volume on this player. This API is recommended for balancing
the output of audio streams within an application. Unless you are
writing an application to control user settings, this API should be
used in preference to setStreamVolume(int, int, int) which sets the
volume of ALL streams of a particular type. Note that the passed
volume values are raw scalars. UI controls should be scaled
logarithmically.Parameters
leftVolume left volume scalar
rightVolume right volume scalar
希望有帮助
1
|
用于提高音量
1
2 |
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); |
用于降低音量
1
2 |
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI); |
隐藏音量控制 UI:
1
|
提高音量
1
2 |
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, 0); |
用于降低音量
1
2 |
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, 0); |
您可以使用
1
2 3 4 5 6 7 8 9 10 11 |
val audio = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC) val maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC) if ( level > twintyVolume) { |
在此处阅读此页面。它解释得很好。
基本上,除非您的应用是替代闹钟,否则您需要在”onCreate()”函数中进行以下调用:
1
|
setVolumeControlStream(AudioManager.STREAM_MUSIC);
|
通过这种方式,您可以使用硬件按钮创建应用的音量。
代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
try { float count = 100 * 0.2f; Log.d("–count_float", count +""); Log.d("–count_final", Math.round(count) +""); Log.d("–count_volume", new PreferenceMotionSensor(mContext).getStreamVolume()); mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, Math.round(count), 0); } catch (Exception e) { Log.d("–Error", e.getMessage()); } |
输出
1
2 3 |
D/–count_float: 20.0
D/–count_final: 20 D/–count_volume: 100 |
以下代码将音量设置为最大级别 (getStreamMaxVolume())。
1
2 |
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setStreamVolume(AudioManager.STREAM_MUSIC,am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),0); |
试试这个
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
protected static void setVolume(int volume) { currentVolume = volume; { if (volume == 1) { volume = 2; } try { float vol = ((float) volume / CONSTANT.SYSTEM_MAX_VOLUME); mediaPlayer.setVolume(vol, vol); } catch (Exception e) { e.printStackTrace(); } } } |
记得设置左右扬声器音量。
1
2 3 |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/267553.html