为随机播放器调试bluej

yrwegjxp  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(364)

我正在尝试用bluej做一个随机的方法来播放播放列表中的一首随机歌曲,然后继续。我的问题是,它只是播放一首歌,然后停止。这是我的密码。希望有人能帮我
https://gist.github.com/anonymous/9493432
我的错误是所有的歌曲同时开始。这是我的密码:

public void randomAllTracks(int index){ 
    if(indexValid(index)) { 
        for(Track track : tracks) { 
            player.startPlaying(track.getFilename()); 
            System.out.println("Now playing: " + track.getArtist() + " - " + track.getTitle()); 
            System.out.println(); 
            int randomTrack = (int)(Math.random() * tracks.size()); 
         }
    }
}
6ss1mwsb

6ss1mwsb1#

要获取始终是有效索引的随机轨迹,请执行以下操作:

int randomTrack = (int)(Math.random() * tracks.size());

您可以删除方法randomtrack(),因为您不需要它。
在类musicplayer中需要某种类型的指示来检查曲目是否完成。这里用trackfinished表示。您可以在播放歌曲时查看该变量。

boolean trackFinished = true;

public void randomAllTracks(int index) { 
    while (true) {
        if (trackFinished) {
            playTrack((int)(Math.random() * tracks.size()));
            trackFinished = false;
        }
    }
}

音乐层代码:

public class MusicPlayer
{
    // The current player. It might be null.
    private AdvancedPlayer player;
    boolean finished = true;

    //some code

    public void startPlaying(final String filename)
    {
        try {
            setupPlayer(filename);
            Thread playerThread = new Thread() {
                public void run()
                {
                    try {
                        trackFinished = false;
                        player.play(5000);
                    }
                    catch(JavaLayerException e) {
                        reportProblem(filename);
                    }
                    finally {
                        killPlayer();
                        trackFinished = true;
                    }
                }
            };
            playerThread.start();
        }
        catch (Exception ex) {
            reportProblem(filename);
        }
    }
}

相关问题