kevdliu
kevdliu

Reputation: 1819

create slider to change android volume?

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!

Upvotes: 10

Views: 17190

Answers (3)

Mark Lee
Mark Lee

Reputation: 335

Six years later, this slightly altered version works for me in Android Studio 3.1. The IDE said I had to declare AudioManager final:

        /* 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

Upvotes: 0

JimsJump
JimsJump

Reputation: 31

Travis at the New Boston has a great Video Tutorial on this here: http://www.youtube.com/watch?v=8sr2Y6Aff6Y

Source code for the tutorials can be found here: http://www.mybringback.com/bringers/android/thenewboston-android-series/828/thenewboston-sample-projects/

Upvotes: 1

Alan Moore
Alan Moore

Reputation: 6575

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

Upvotes: 22

Related Questions