以随机顺序播放曲目 java

playing track in random order java

我走在正确的轨道上吗?这必须以随机顺序播放 arraylist 中的每个曲目一次。

public void randomAllTrack() { 

    int shuffle = getNumberOfTracks();
    int shuffleplay = randomTrack.nextInt(shuffle);
    Track track = tracks.get(shuffleplay);
    int i=0;

    while(i < getNumberOfTracks())
    {player.startPlaying(track.getFilename());
        System.out.println("Now playing: " + track.getArtist() + " - "
        + track.getTitle());
        i++;}
}

假设 tracksCollection,您可以使用 for-each loop after doing a Collections.shuffle(List),而我可以使用格式化 IO。像

public void randomAllTrack() {
    List<Track> randomTracks = new ArrayList<>(tracks);
    Collections.shuffle(randomTracks);
    for (Track track : randomTracks) {
        player.startPlaying(track.getFilename());
        System.out.printf("Now playing: %s - %s%n", track.getArtist(),
                track.getTitle());
    }
}

创建 List 并使用 Collection 如果您只需要初始随机播放: List<Track> tracks = new ArrayList<>(); Collections.shuffle(tracks); for (Track track : tracks) { System.out.println("Playing track: " track.getFilename()); }