Search code examples
androidmedia-player

How make a Button on/off music android


i'am trying to develop an app in android with 2 buttons. the first button must pause and restart the music if you state is on or off. but this code doesn't works, why?

public class MainActivity extends Activity {
MediaPlayer sound;
Boolean pulsado=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    sound=MediaPlayer.create(getBaseContext(),R.raw.gaitas);
    sound.setLooping(true);
    sound.start();
}
public void boton1(View v){
    if(pulsado==false){
        sound.stop();
        pulsado=true;
    }else{
        sound.reset();
    }

}
public void boton2(View v){
    Intent i=new Intent(this,ActivityB.class);
    startActivity(i);
}

Solution

  • Android documentation says about MediaPlayer.reset() -- Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

    For your purpose, you could use MediaPlayer.create(...) again to setDataSource to the MP and prepare it for playing.

    if (pulsado == false) {
        sound.stop();
        sound.reset();
        pulsado = true;
    } else {
        sound = MediaPlayer.create(getBaseContext(), R.raw.song);
        sound.setLooping(true);
        sound.start();
        pulsado = false;
    }
    

    If you are looking for pausing the song, you could rather call sound.pause() and in else block simple sound.start() should be enough to resume the song.