Search code examples
androidvolumeandroid-audiomanager

how to sync music volume with ring volume using AudioManager


here is my code:

   if(setting.getBoolean("autoVolume",false))
     {       
         setVolume(c,AudioManager.STREAM_MUSIC,manager.getStreamVolume(AudioManager.STREAM_RING));  
         Log.e("max ring volume",manager.getStreamMaxVolume(AudioManager.STREAM_RING)+"");//result:7
         Log.e("max music volume",manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)+"");//result 15
     }

setVolume function:

     private void setVolume(Context c,int streamName,int volume){

     AudioManager manager =
             (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
     manager.setStreamVolume(streamName,volume,0);
 }

i want sync music volume with ring volume but it doesn't work because they haven't same range(max music volume is 15 and max ring volume is 7!)

i want a simple math way thanks


Solution

  • If you have numbers x in the range [a,b] and you want to transform them to numbers y in the range [c,d] you need to do this:

    y = ((x−a) * (d−c) / (b−a)) + c
    

    In your case:

    • x: ring volume
    • [a,b]: 0-7
    • [c,d]: 0-15
    • y: music volume

    You get:

    music_volume = ring_volume * (15 / 7)