create slider to change android volume?

kevdliu picture kevdliu · Sep 18, 2011 · Viewed 14.9k times · Source

Can someone give me an sample code for changing volume through a slider? I searched and a lot of tutorials requied me to create a whole new class. Is there an easier way?

Thanks!

Answer

Alan Moore picture Alan Moore · Sep 18, 2011

Add this to your OnCreate, you have to put your seekbar into the layout xml file:

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