为什么mediaPlayer类在这种情况下不起作用?

时间:2015-05-20 09:34:44

标签: java javafx

所以我正在尝试创建自己的mp3播放器。 mediaPlayer.play()方法有效,但暂停不起作用。 有人可以帮助我吗?

 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();
        }

    }

1 个答案:

答案 0 :(得分:1)

看起来你正在MediaPlayer的第二个实例上调用Pause。

...
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();
        }
    ...

您需要在该事件范围之外实例化mediaPlayer。试试这样:

   // 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();
    }

}