简体   繁体   中英

Playing an ArrayList of MediaPlayer objects

Context:

I'm making a game with a huge group of people for a uni project, and I want to make a music class where someone can write Music music = New Music("song1.mp3, song2.mp3, song3.mp3") and music.play() somewhere else and it will play those songs in order and forever. The files must be stored in a particular location, my code at the moment takes care of this. I want it to be this way so it's easy for others to put their own music into the program for whatever area of the game they're implementing (the tutors will like me doing this).

At the moment my code initializes with

private ArrayList<MediaPlayer> playlist;

public Music(ArrayList<String> playlistStrings){
    playlist = new ArrayList<MediaPlayer>();
    for(int i = 0; i<playlistStrings.size(); i++){
        URL url = Music.class.getResource("../Music/" + playlistStrings.get(i));
        Media media = new Media(url.toString());
        MediaPlayer player = new MediaPlayer(media);
        playlist.add(player);
    }
    System.out.println(playlist);
}

tl;dr

I have an ArrayList of MediaPlayer objects and I want to play them all, and loop the entire playlist. I understand I'm supposed to use a Listener at some point... but I'm still confused because I want to have a listener but I also want it in some kind of loop... Does anyone have an example of this somewhere? I have already looked at https://gist.github.com/jewelsea/1446612 and extracted his playlist code, but it did not work for me. Thanks!

edit: The following code can play a list of tracks, but I can't figure out how to get the entire list to repeat indefinitely.

public void play(){
    System.out.println(trackIndex);
    player = playlist.get(trackIndex); 
    player.play();
    player.setOnEndOfMedia(new Runnable() {
        @Override public void run() {
            System.out.println(trackIndex);
            player.stop(); 
            if(trackIndex == (playlist.size()-1)){
                trackIndex = 0;
            }
            trackIndex++;
            player = playlist.get(trackIndex);
            player.play();
        }
    });
}
  • 使用对方法的递归调用修复了此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM