所以我正在制作一个带有ListView
javafx的mp3播放器,我拖放歌曲,然后我选择一首歌并按播放播放它,你明白了......
麻烦的是,用我目前的代码,我不能播放超过两首歌曲的序列:/(播放所选歌曲,播放旁边的歌曲然后停止)。
这是代码:
public class MainController implements Initializable {
@Override
public void initialize(URL location, ResourceBundle resources) {
list.setItems(tracklist);
}
private MediaPlayer player;
private Duration pausetime = null;
private int i;
ObservableList<String> tracklist = FXCollections.observableArrayList();
ArrayList<File> playlist = new ArrayList<File>();
ArrayList<MediaPlayer> players = new ArrayList<MediaPlayer>();
@FXML
private Slider slider;
@FXML
private Button open;
@FXML
private Label csong;
@FXML
private ListView<String> list;
public void getsongfromlist(){
i = list.getSelectionModel().getSelectedIndex();
}
public void slide(int a){
slider.setMin(0.0);
slider.setValue(0.0);
player.currentTimeProperty().addListener(new ChangeListener<Duration>(){
@Override
public void changed(ObservableValue<? extends Duration> observableValue, Duration duration,
Duration current) {
// TODO Auto-generated method stub
slider.setMax(players.get(a).getTotalDuration().toSeconds());
slider.setValue(current.toSeconds());
}
});
}
public void move(){
player.seek(Duration.seconds(slider.getValue()));
}
public void play(){ //This is where im getting it wrong
if (player != null){
player.stop();
}
this.player = players.get(i);
player.play();
slide(i);
csong.setText(playlist.get(i).getName());
for (int j = 0; j < players.size(); j++){
player.setOnEndOfMedia(new Runnable(){
@Override public void run(){
i++;
list.getSelectionModel().select(i);
player = players.get(i);
player.play();
slide(i);
csong.setText(playlist.get(i).getName());
}
});
}
}
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasFiles()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
}
public void dropped(DragEvent event){
Dragboard db = event.getDragboard();
event.acceptTransferModes(TransferMode.COPY);
boolean success = false;
if (db.hasFiles()){
success = true;
for (File file:db.getFiles()){
tracklist.add(file.getName());
playlist.add(file);
try {
final Media media = new Media(file.toURI().toURL().toString());
final MediaPlayer set = new MediaPlayer(media);
players.add(set);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
event.setDropCompleted(success);
event.consume();
}
}
答案 0 :(得分:1)
未经测试,但请尝试更换
for (int j = 0; j < players.size(); j++){
player.setOnEndOfMedia(new Runnable(){
@Override public void run(){
i++;
list.getSelectionModel().select(i);
player = players.get(i);
player.play();
slide(i);
csong.setText(playlist.get(i).getName());
}
});
}
与
player.setOnEndOfMedia(new Runnable(){
@Override
public void run() {
i++ ;
play();
}
});
并移动线
list.getSelectionModel().select(i);
从endOfMedia
侦听器到play()
方法的主体。
答案 1 :(得分:0)
我会尝试更改if player != null
。
尝试使用其他值,例如您要播放的歌曲数量。