RSS

Android SeekBar to set the volume.

13 Jul


Below is how you can use a SeekBar to adjust the volume:

package com.learning.gilo;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class SetVolume extends Activity implements OnSeekBarChangeListener{

	SeekBar sb;
	MediaPlayer mp;
	AudioManager am;
	int Volume=0;
	
	protected void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.seek);
		
		sb  =(SeekBar) findViewById(R.id.sbVolume);
		mp = MediaPlayer.create(this, R.raw.say);
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		
		mp.start();
		int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int curVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		
		sb.setMax(maxVolume);
		sb.setProgress(curVolume);
		
		sb.setOnSeekBarChangeListener(this);
	}
	
	protected void onPause(){
		super.onPause();
		
		mp.pause();
		//mp.release();
	}
	protected void onResume(){
		super.onResume();
		
		mp.start();
		
	}
	
	public void onProgressChanged(SeekBar seekb, int progress, boolean arg2) {
			am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
			Volume = progress;		
	}

	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "Volume: " + Integer.toString(Volume), Toast.LENGTH_SHORT).show();
	}
}


Advertisements
 
10 Comments

Posted by on July 13, 2012 in Uncategorized

 

10 responses to “Android SeekBar to set the volume.

  1. Véronique

    March 15, 2013 at 10:41 pm

    hi! i’m new to android programming and i can’t get the application to run because i’m not sure about you put in your layout main_activity.xml file and in your strings.xml…?
    also, what kind of file do you play for the sound?
    thank you for your help!

     
  2. Gilbert Kimutai

    March 16, 2013 at 9:11 am

    In my layout main_activity.xml (mine is seek.xml), I have a SeekBar with the id sbVolume. I also have a folder in the res folder known as raw that has an mp3 file known as say.mp3. I have not touched the strings.xml. Hope this helps.

     
  3. Véronique

    March 16, 2013 at 11:51 am

    thank you very much, it works now! 😀 and i also wanted to add a checkbox to enable/disable the sound. do i have to use preferences to do that or is there a simpler way? can i just put a condition on the checkbox (see if it’s checked or not) and use AudioManager?

     
    • Gilbert Kimutai

      March 16, 2013 at 12:42 pm

      yeah that should do. You can have a listener for the checkbox and then set the volume to 0 – am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);

       
  4. Véronique

    March 16, 2013 at 3:12 pm

    that’s great thanks! it works fine except for a little detail ; if i disable the sound then drag the volume bar up, the sound comes back but it is lower than when i reactivate the sound.
    So i have 2 questions:
    – how do i make sure the sound stays mute when the box isn’t checked even if i move the seek bar?
    – when the box is checked, is my audio manager here right : am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, curVolume) ?

    here is your code completed with my CheckBox:

    public class MainActivity extends Activity implements OnSeekBarChangeListener{
     
        SeekBar sb;
        CheckBox cb;
        MediaPlayer mp;
        AudioManager am;
        int Volume=0;
         
        protected void onCreate(Bundle b){
            super.onCreate(b);
            setContentView(R.layout.activity_main);
             
            sb  =(SeekBar) findViewById(R.id.sbVolume);
            cb = (CheckBox)findViewById(R.id.cb);
            mp = MediaPlayer.create(this, R.raw.umbrella);
            am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
             
            mp.start();
            int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int curVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
             
            sb.setMax(maxVolume);
            sb.setProgress(curVolume);
             
            sb.setOnSeekBarChangeListener(this);
            cb.setOnClickListener(checkedListener);
            
            cb.isChecked();
       }
        
        
        // Listener du bouton son.
        private OnClickListener checkedListener = new OnClickListener() {
          @Override
          public void onClick(View v) {
              int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
              int curVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
              
              if(!(cb.isChecked()))
                 // Mettre le volume à 0 si le bouton son n'est PAS coché
                 am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
              
              else if(cb.isChecked())
            	 am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, curVolume);  
          }
        };
         
        protected void onPause(){
            super.onPause();
             
            mp.pause();
            //mp.release();
        }
        protected void onResume(){
            super.onResume();
             
            mp.start();
             
        }
         
        public void onProgressChanged(SeekBar seekb, int progress, boolean arg2) {
                am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                Volume = progress;      
        }
     
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
             
        }
     
        public void onStopTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Volume: " + Integer.toString(Volume), Toast.LENGTH_SHORT).show();
        }
    }
    
     
  5. Gilbert Kimutai

    March 16, 2013 at 3:17 pm

    the sound comes back because of the onProgressChanged() method.
    Try:

    public void onProgressChanged(SeekBar seekb, int progress, boolean arg2) {
    if(!cb.isChecked()){
        am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
        Volume = progress;
    }
    }
    
     
  6. Véronique

    March 16, 2013 at 3:38 pm

    thanks! now the sound does stay mute when the box isn’t checked but there is one weird thing : if i set the volume with the seek bar (with the sound enabled) and then i disable and re-enable the sound, the sound will come out louder than it was before, is that due to my am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, curVolume) ? did i put the right parameters there?

     
  7. Gilbert Kimutai

    March 16, 2013 at 5:36 pm

    Yeah you did it slightly wrong, it should be

    am.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume, 0);
    

    The first parameter defines which stream to be set, the second is the volume, and third is the flags. Check out http://developer.android.com/reference/android/media/AudioManager.html#setStreamVolume(int, int, int)

     
  8. Véronique

    March 16, 2013 at 6:20 pm

    thank you so much for your help, it’s very nice!! 🙂

     
  9. Jovet Alabastro

    October 30, 2013 at 12:25 pm

    Please help me in how to globally turn on/off sounds when I click the button settings it would be appear a toggle button message dialog.

    I have there 5 classes on my game, they are:

    New Game
    Settings {on/Off} ->that’s my problem.
    Help
    About
    Exit
    I’m currently engage that scenario.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: