Android : How to set MediaPlayer volume programmatically?

后端 未结 10 514
你的背包
你的背包 2020-12-08 04:17

How to set the mediaplayer volume programmatically. I use it for alarm notification. Any help is highly appreciated and thanks in advance.

相关标签:
10条回答
  • 2020-12-08 04:30

    Read this page right here. It explains very well. Basically, unless your app is a replacement alarm clock, you need to make the following call in the "onCreate()" function:

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    

    In this way you can create the volume of your app using the hardware buttons.

    0 讨论(0)
  • 2020-12-08 04:37

    Remember to set left and right speaker volumes.

    if (System.nanoTime() == alarm){
        yourMediaPlayer.setVolume(volume, volume)}
    }
    
    0 讨论(0)
  • 2020-12-08 04:39

    You can do the below using Kotlin, this code will check if the media volume is more than 20% of the maximum volume of the device, and will reduce it to be 20% only.

        val audio = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
    
        val maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val percent = 0.2f
        val twintyVolume = (maxVolume * percent).toInt()
    
        if ( level > twintyVolume) {
            Toast.makeText(this,"audio level is $level", Toast.LENGTH_LONG).show()
            audio.setStreamVolume(AudioManager.STREAM_MUSIC,twintyVolume,0)
        }
    
    0 讨论(0)
  • 2020-12-08 04:39

    Code:

    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());
     }
    

    Output

    D/--count_float: 20.0
    D/--count_final: 20
    D/--count_volume: 100
    
    0 讨论(0)
  • 2020-12-08 04:41

    You do have the setVolume method in the MediaPlayer class. See here

    0 讨论(0)
  • 2020-12-08 04:42

    Try This

    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();
                }
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题