0

This code is not working after one time. After clicking it once it stops the music but after clicking it again it is not starting the music again.

ToggleButton sound;
MediaPlayer sip;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sound = (ToggleButton) findViewById(R.id.Sound1);
    sip = MediaPlayer.create(Naruto.this, R.raw.sip2);
    sip.start();
    sound.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            if (sound.isChecked() == true) {
                sip.start();
            } else {
                sip.start();
            }
        }
    });
}
Antti29
  • 2,953
  • 12
  • 34
  • 36

3 Answers3

0

Try below code;

     sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Boolean switchState = holder.simpleSwitch.isChecked();

                if (switchState==true)
                {
                   sip.start();
                }
                else
                {
                   sip.stop();
                }
            }
        });
Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
0

The MediaPlayer needs to be configured. Try this:

sound.setOnClickListener(new View.OnClickListener(){
    public void onClick(View arg0) {
        if (sound.isChecked()==(true)){
            sip.setDataSource(filePath);
            sip.prepare();
            sip.start();
        }else
        {
            sip.release();
            sip = null;
        }

}});
Laur89
  • 105
  • 7
  • 1
    `sip.setDataSource(filePath);` generate null pointer exception when toggle button clicked again because you initialize `sip = null` in else part – Vishal Yadav Oct 24 '17 at 10:26
  • yes, you have to replace `filePath` with your file path. Try to replace that line with `sip = MediaPlayer.create(Naruto.this, R.raw.sip2);` . Please tell me if it works – Laur89 Oct 24 '17 at 10:37
0

You can try this.

sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
        if(isChecked)
        {
            sip.start();
        }
        else
        {
            sip.stop();
        }
    }
});
Rishabh Sharma
  • 270
  • 5
  • 17