Use toggle button to control sound

2.4k Views Asked by At

I need my app to play all the sounds when toggle button is checked and stop playing them when it is unchecked.By all sounds I mean the sound played when other buttons present in the activity and other activities are pressed.

Following is my toggle button:

<ToggleButton
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:id="@+id/toggleButton"
    android:button="@drawable/check"
    android:background="@null"
    android:onClick="togglesound"
   />

Check.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/speaker"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/stopsound"
android:state_checked="false"/>
</selector>

I have taken a static variable "play" whose value I intend to set to 1 when toggle button is checked and to 0 when it is not.

 public void togglesound(View view) {
    boolean on = ((ToggleButton) view).isChecked();

    if (on) {
     play=1;
        // Enable sound
    } else {
       play=0;
        // Disable sound

    }

After this I put the condition using "play" to play the required sound

 if(play==1) 
 {
 over = MediaPlayer.create(Play.this, R.raw.over);
 over.start();
 over.setOnCompletionListener(
 newMediaPlayer.OnCompletionListener()
 {    
 public void onCompletion(MediaPlayer mp) {
 mp.release();
                }

            });
        }
 else
 {}

The problem I am facing is that the toggle button works fine for the first time it is clicked but then plays the sound even if the toggle button is unchecked.

1

There are 1 best solutions below

0
On BEST ANSWER

Finally fixed it!!

Instead of using "play" and "on" I am using only "play" which is a static boolean variable.So,the code reduces to -

public void togglesound(View view) {
      play = ((ToggleButton) view).isChecked();
      }

And I had to add a few lines to save the state of the toggle button.

 private static Bundle bundle = new Bundle();
 ToggleButton tg=(ToggleButton)findViewById(R.id.toggleButton);

   public void onPause() {
    super.onPause();
    bundle.putBoolean("ToggleButtonState", play);
     }

@Override
public void onResume() {
    super.onResume();
    tg.setChecked(bundle.getBoolean("ToggleButtonState",false));
     }