Maksymilian Konarski
Maksymilian Konarski

Reputation: 101

Mp3 player JavaFX

For several hours I have been trying to add a method that will open my mp3 files and open them one by one in the queue. But I don't have an idea how to do it. When it comes to a single file, it is not a problem for me to open it and play. So I was thinking about threads or getDuration method from Media(JavaFX) class. When I am using getDuration I am receiving Nan, I wrote that I need to wait for setOnReady for my mediaPlayer object, so I've created a Thread.sleep, but the result was the same as previous. Thanks in advance! Here is some code (I know, I described the issue a little bit confusing):

Fields

private static MediaPlayer mediaPlayer;
private static FileChooser fileChooser;
private static Stage stage;
private List<File> selectedFiles;
private String path;

Play method

@FXML
void play() {
    Media media;
    try {
    for (int i = 0; i < selectedFiles.size(); i++) {
        Thread thread = new Thread();
        path = selectedFiles.get(i).getAbsolutePath().replace("\\", "/");
        media = new Media("file:///" + path);
        mediaPlayer = new MediaPlayer(media);

        Thread.sleep(5000);

        mediaPlayer.setOnReady(() -> mediaPlayer.play());
        System.out.println(media.getDuration().toSeconds());
        thread.setName("thread " + i);
        System.out.println(thread.getName());
    }
}catch (Exception e){
        System.out.println("You need to choose the music file like mp3 etc");
        System.out.println("The error name:\n"+e);
    }

}

MultipleDialog method

enter code here @FXML
void openDirectory(){
    try {
        fileChooser = new FileChooser();
        FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter("mp3 files (*.mp3)", "*.mp3");
        fileChooser.getExtensionFilters().add(extensionFilter);
        selectedFiles = fileChooser.showOpenMultipleDialog(null);


    }catch (Exception e){
        System.out.println("No file");
    }

Upvotes: 0

Views: 507

Answers (1)

Jacob B.
Jacob B.

Reputation: 433

There could be a very easy way to do this.

Store all the files you open into a List. Once the media file is done playing (endOfMedia), play the next file in the List.

Good luck!

Upvotes: 1

Related Questions