How To Add Sound On The Toggle Button?
I implement a Toggle Botton on Activity. I wanted to add Sound (on & off) to that button but I am not able to add sound on it. This is the code I wrote. public class SoundLayou
Solution 1:
You can make use of setOnCheckedChangeListener of toggle button.In this u get a paramater indicating if the button is in on or off state.Based on it u can play hte required sound using media player.
ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton);
tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
System.out.println("ischecked>>>>>>>>>>>>>>>>>>>>>>>>>.");
else
System.out.println("not checked>>>>>>>>>>>>>>>>>>>>>>>>>.");
}
});
Solution 2:
Just place the sound file in /res/raw (after creating the folder) and then use MediaPlayer to init, start and then stop playing the sound.
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1); mp.start();
And then you get all the start/stop/reset/pause/release methods from mp.
Solution 3:
public void togglesound(View v) {
int play;
boolean on = ((ToggleButton) v).isChecked();
if (on) {
play = 1;
// Enable sound
if (play == 1) {
cleanUpMediaPlayer();
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(10000);//TIME TO VIBRATE
mp = MediaPlayer.create(this, R.raw.musicmachine);
mp.start();
} else {
play = 0;
// Disable sound
stopMediaPlayer();
}
}
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Displayone.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}
Post a Comment for "How To Add Sound On The Toggle Button?"