2011-09-18 11 views

risposta

18

Aggiungi questo al tuo OnCreate, dovete mettere il vostro SeekBar nel file di layout xml:

audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); 
    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
    int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
    SeekBar volControl = (SeekBar)findViewById(R.id.volbar); 
    volControl.setMax(maxVolume); 
    volControl.setProgress(curVolume); 
    volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
     @Override 
     public void onStopTrackingTouch(SeekBar arg0) { 
     } 

     @Override 
     public void onStartTrackingTouch(SeekBar arg0) { 
     } 

     @Override 
     public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { 
      audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0); 
     } 
    }); 
+0

Come faccio se il mio audio si avvia altrove (ad esempio in un servizio)? Ricevo una NullPointerException in onProgressChanged quando provo a spostare la barra. – ShadowGod

+0

Probabilmente dovresti metterlo in una domanda separata. Probabilmente dovrai chiamare il tuo servizio per regolare il volume. –

+0

Vedo. Grazie Alan per una rapida risposta! – ShadowGod

0

Sei anni dopo, questa versione leggermente modificata funziona per me in Android Studio 3.1. L'IDE ha dichiarato che dovevo dichiarare final AudioManager:

 /* volume slider*/ 
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); 
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
SeekBar volControl = (SeekBar)findViewById(R.id.volControl); 
volControl.setMax(maxVolume); 
volControl.setProgress(curVolume); 
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
    @Override 
    public void onStopTrackingTouch(SeekBar arg0) { 
    } 

    @Override 
    public void onStartTrackingTouch(SeekBar arg0) { 
    } 

    @Override 
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { 
     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0); 
    } 
}); 

//end Volume slider 
Problemi correlati