april21
april21

Reputation: 115

Why does the mediaPlayer class not work in this case?

So I'm trying to create my very own mp3 player. The mediaPlayer.play() method works but pause doesn't work. Can someone help me out?

 public void audioPlayerButtons(ActionEvent actionEvent) {

        String bip = getClass().getResource("Songs/Sing.m4a").toExternalForm();
        Media hit = new Media(bip);
        MediaPlayer mediaPlayer = new MediaPlayer(hit);

        if (actionEvent.getSource() == playbtn) {
            mediaPlayer.play();

            nowPlaying.setText("Now Playing");
            songPlayingName.setText("Sing");

        } else if (actionEvent.getSource() == pausebtn) {
            mediaPlayer.pause();


        } else if (actionEvent.getSource() == forwardbtn) {
            mediaPlayer.stop();

        } else if (actionEvent.getSource() == backwardbtn) {
            mediaPlayer.isAutoPlay();
        }

    }

Upvotes: 0

Views: 70

Answers (1)

Stultuske
Stultuske

Reputation: 9437

It looks like you are calling Pause on a second instance of MediaPlayer.

...
MediaPlayer mediaPlayer = new MediaPlayer(hit);
// each time you hit a button, you create a new MediaPlayer

        if (actionEvent.getSource() == playbtn) {
            mediaPlayer.play();
            // first time, you call play, so it plays
            nowPlaying.setText("Now Playing");
            songPlayingName.setText("Sing");

        } else if (actionEvent.getSource() == pausebtn) {
            // pause does work, but it is not the same instance that is playing
            mediaPlayer.pause();
        }
    ...

You'll need to instantiate mediaPlayer outside the scope of that event. Try like this:

   // instance variables
    String bip = getClass().getResource("Songs/Sing.m4a").toExternalForm();
    Media hit = new Media(bip);
    MediaPlayer mediaPlayer = new MediaPlayer(hit);

public void audioPlayerButtons(ActionEvent actionEvent) {        

    if (actionEvent.getSource() == playbtn) {
        mediaPlayer.play();

        nowPlaying.setText("Now Playing");
        songPlayingName.setText("Sing");

    } else if (actionEvent.getSource() == pausebtn) {
        mediaPlayer.pause();


    } else if (actionEvent.getSource() == forwardbtn) {
        mediaPlayer.stop();

    } else if (actionEvent.getSource() == backwardbtn) {
        mediaPlayer.isAutoPlay();
    }

}

Upvotes: 1

Related Questions