How can I make the same button that plays the audio, stop when the button is clicked?

Viewed 75

How can I make the same button that plays the media file, stop it? This is so far what I have tried but the problem is whenever I pressed the buttons to try to play and stop the music, it gives an error in the run log and nothing happens. I`m still learning things so if someone could explain how to play and stop audio the correct way and whatever else is required to make it function correctly that would be great. I am relatively familiar with the MediaPlayer states, its just I have trouble putting together the code correctly. Thank you.

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final MediaPlayer musicMP = MediaPlayer.create(this, R.raw.lofi);

        Button playMusic = this.findViewById(R.id.bell_peppers_and_beef);

        playMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                musicMP.start();
                musicMP.stop();
            }
        });}}

Run Log Error:

E/MediaPlayerNative: start called in state 64, mPlayer(0x720df4c340) V/MediaPlayerNative: message received msg=100, ext1=-38, ext2=0 E/MediaPlayerNative: error (-38, 0) V/MediaPlayer-JNI: stop V/MediaPlayerNative: stop E/MediaPlayerNative: stop called in state 0, mPlayer(0x720df4c340) V/MediaPlayerNative: message received msg=100, ext1=-38, ext2=0 E/MediaPlayerNative: error (-38, 0)

1 Answers

MediaPlayer has the isPlaying() method:

if (mediaPlayer.isPlaying()) {
    mediaPlayer.pause();
} else {
    mediaPlayer.start();
}

But if you want to call stop(), then you need also to call prepare() to be able to start() again (you can't go directly from stopped state to started state):

if (mediaPlayer.isPlaying()) {
    mediaPlayer.stop();
    mediaPlayer.prepare();
} else {
    mediaPlayer.start();
}

You can check out all allowed transitions between states in documentation.

Related