Play one song after the another javafx

后端 未结 1 1066
忘掉有多难
忘掉有多难 2021-01-24 11:46

I\'m trying to get song location from DB and play one song after the another but in here it plays the last song in the database and stops playing. I want to play the first song,

1条回答
  •  再見小時候
    2021-01-24 12:27

    You have a logical issue with your code. Instead of just changing the media, you are trying to add everything again in the loop. The loop just builds everything again for you and at the end you just get the last media playing. You need to play the first one and on its completion, add the second one, play it and so on.

    Replace the for loop with this piece of beauty.

    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.media.MediaView;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    
    public class Example extends Application {
    
        final MediaView view = new MediaView();
        Iterator itr ;
        @Override
        public void start(Stage stage) throws Exception {
            final Group root = new Group();
            List list = new ArrayList();
            itr = list.iterator();
            //Plays the first file
            play(itr.next());
            root.getChildren().add(view);
            Scene scene = new Scene(root, 400, 400, Color.BLACK);
            stage.setScene(scene);
            stage.show();
        }
        public void play(String mediaFile){
            Media media = new Media(mediaFile);
            MediaPlayer player = new MediaPlayer(media);
            view.setMediaPlayer(player);
            player.play();
            player.setOnEndOfMedia(new Runnable() {
                @Override
                public void run() {
                    player.stop();
                    if (itr.hasNext()) {
                        //Plays the subsequent files
                        play(itr.next());
                    }
                    return;
                }
            });
        }
        public static void main(String[] args) {
            launch(args);
        }
    } 
    

    0 讨论(0)
提交回复
热议问题