从文本文件读取的音乐播放器一次播放所有片段 Javafx

Music Player reading from text file plays all pieces at once Javafx

您好,我目前正在尝试将音乐添加到我的应用程序中,现在我正在让程序从文件中获取文件名并播放它们。由于应用程序中的一个缺陷,我尝试通过让 Thread 休眠来调解音乐播放器同时播放两首曲子,虽然听起来不错但对我没有帮助。下面是我的代码:

    public static class MusicPlayerService extends Service<Void>
{
    public static File[] musicArray = new File[2];
    public static int fileNumber = 0;

    @Override
    protected Task<Void> createTask(){
        Scanner musicListReader;
        try {
            musicListReader = new Scanner(new File("Music_PlayList.txt"));
            while(musicListReader.hasNext())
            {
                musicArray[fileNumber] = new File(musicListReader.next());
                String uriString = musicArray[fileNumber].toURI().toString();
                Media media = new Media(uriString);
                MediaPlayer player = new MediaPlayer(media);
                player.play();
                Thread.sleep((long) media.getDuration().toMillis());
                fileNumber++;
            }
        } catch (FileNotFoundException | InterruptedException e1) {
            e1.printStackTrace();
        }   
        return null;
    }
}

考虑使用事件驱动的方法,而不是循环和休眠的方法。您可以向媒体播放器注册一个 onStopped 处理程序,然后从那里开始下一首歌曲(如果有下一首歌曲)。这样,您也不需要使用后台线程。

类似于:

Queue<File> musicList = new LinkedList<File>();

try (Scanner musicListReader = new Scanner(new File("Music_PlayList.txt"))) {

    while (musicListReader.hasNext()) {
        musicList.add(new File(musicListReader.next()));
    }

} catch (Exception e) {
    e.printStackTrace();
}

playNextMusicFile(musicList);

// ...

private void playNextMusicFile(Queue<File> musicList) {
    if (musicList.isEmpty()) {
        return ;
    }

    Media media = new Media(musicList.remove().toURI().toString());
    MediaPlayer player = new MediaPlayer(media);
    player.setOnEndOfMedia(() -> {
        player.dispose();
        playNextMusicFile(musicList);
    });
    player.play();
}