无法让.mp3停止使用JavaFX媒体播放器

时间:2015-03-24 20:11:03

标签: java javafx mp3 media-player scenebuilder

所以我试图使用javafx和scenebuilder制作自动点唱机应用。它有一个键盘,我在其中键入标签中的歌曲编号,标签上的文本转换为int并传递给track()方法,该方法从数组中选取一个轨道(该数组是一个占位符未来的发烧友) play()方法播放轨道很好...... 控制器类的代码:

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class MainController implements Initializable {

@Override
public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

}

@FXML
private Label number;

public void zero(ActionEvent event){

    number.setText(number.getText() + "0");
}

public void one(ActionEvent event){

    number.setText(number.getText() + "1"); 
}

public void two(ActionEvent event){

    number.setText(number.getText() + "2");
}

public void three(ActionEvent event){

    number.setText(number.getText() + "3");
}

public void four(ActionEvent event){

    number.setText(number.getText() + "4"); 
}

public void five(ActionEvent event){

    number.setText(number.getText() + "5");     
}

public void six(ActionEvent event){

    number.setText(number.getText() + "6");     
}

public void seven(ActionEvent event){

    number.setText(number.getText() + "7"); 
}

public void eight(ActionEvent event){

    number.setText(number.getText() + "8");     
}

public void nine(ActionEvent event){

    number.setText(number.getText() + "9");
}

public void clear(){
    number.setText("");
}

public MediaPlayer track(){
        URL[] songs = new URL[]{
        getClass().getResource("/res/03. Eyes On Fire.mp3"),
        getClass().getResource("/res/05,Graveyard-Endless Night.mp3"),
        getClass().getResource("/res/10 Nas - It Ain't Hard To Tell.mp3")
};

 final Media media = new Media(songs[Integer.parseInt(number.getText())].toString());
 final MediaPlayer mediaplayer = new MediaPlayer(media);
 return mediaplayer;
}

public void play(){
    track().play();

}

public void stop(){
    track().stop();
}

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

每次调用时,track()方法都会创建一个新MediaPlayer。因此,当您致电stop()时,您在与您呼叫play()的实例不同的实例上呼叫它,而您呼叫play()的实例永远不会停止。

您需要保留对“当前”MediaPlayer的引用。让track()(或者selectTrack()更新该引用,然后您可以在需要时调用stop()。例如:

public class MainController {

    private MediaPlayer player ;

    // ...

    public void selectTrack() {
        URL[] songs = new URL[] { ... } ;
        final Media media = new Media(songs[Integer.parseInt(number.getText())].toString());
        this.player = new MediaPlayer(media);
    }

    public void play() {
        // stop current player:
        if (player != null) {
            player.stop();
        }
        selectTrack();
        player.play();
    }

    public void stop() {
        player.stop();
    }
}