How to turn the volume to max programmatically on android? [duplicate]

試著忘記壹切 提交于 2019-11-26 16:12:52

问题


This question already has an answer here:

  • How to control volume in android? 1 answer

I am writing an app for android that turns up the volume and plays a song for 45 seconds and then stops. That works great, however I can only get the volume to turn up to 50%, Is there a way to turn the volume up to 100% using setVolume()?

This is my code:

final MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);

//plays eye of the tiger for 45 seconds
if (messages.contains("MUSIC ONLY")){

    //turn up the volume
    mp.setVolume(20, 20);
    mp.start();

    //play ring tone for 45 seconds
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            mp.stop();
        }
    }, 45000);
}

回答1:


You can use the following snippet, using AudioManager:

AudioManager am = 
    (AudioManager) getSystemService(Context.AUDIO_SERVICE);

am.setStreamVolume(
    AudioManager.STREAM_MUSIC,
    am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
    0);

This sets the volume to the maximum level (getStreamMaxVolume()) for the STREAM_MUSIC (which is on example a song played). For other types of sounds, use different value, like STREAM_RING etc.



来源:https://stackoverflow.com/questions/15670524/how-to-turn-the-volume-to-max-programmatically-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!