Search code examples
androidandroid-mediaplayer

Play and Pause using the same button


I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again It continues where it left off.

JAVA SIDE;

MediaPlayer ocean;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sound);
    ocean=MediaPlayer.create(Sound.this,R.raw.ocean);
}
public void play(View v){
    ocean.start();
}
public void pause(View V){
    ocean.pause();
}}

ACTIVITY SIDE:

 <Button
    android:id="@+id/play"
    android:layout_width="165dp"
    android:layout_height="0dp"
    android:layout_marginBottom="285dp"
    android:background="@drawable/oceansound"
    android:onClick="play"
    android:text=""/>

Solution

  • Use a flag that indicates if the player is on or off:

    Boolean isOn = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sound);
        ocean=MediaPlayer.create(Sound.this,R.raw.ocean);
    }
    public void play(View v){
        if (!isOn) {
            ocean.start();
            isOn = true;
        } else {
            ocean.pause();
            isOn = false;
        }
    }
    }