Home > Enterprise >  Adding music in android studio (java, MediaPlayer)
Adding music in android studio (java, MediaPlayer)

Time:10-05

   buttonMusic = findViewById(R.id.buttonMus);

    musicSound = MediaPlayer.create(this, R.raw.music);
    buttonClick();
}

private Button buttonMusic;
private MediaPlayer musicSound;

public void buttonClick() {
    buttonMusic.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    soundPlay(musicSound);

                }
            }
    );
}

public void soundPlay(MediaPlayer sound) {
    if (sound.isPlaying()) {
        sound.stop();

    }else {
        sound.start();
        sound.setLooping(true);
    } }

Hello. The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.

CodePudding user response:

you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)

after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick

check out state diagram of MediaPlayer

  • Related