2

我无法一个接一个地播放 MP3 文件,当一个文件完成播放另一个文件时需要开始。我只能开始播放 1 个文件,当我输入代码来启动下一个文件时,它什么也不做。由于某些原因,我无法thread.sleep()在文件期间使用。有没有其他方法可以做到这一点?

//this is the basic code..
playq(String fname){
pl =  Manager.createPlayer(stream,"audio/mpeg");
pl.realize();

pl.prefetch();

pl.start();

// what should i use here?? pls i don't want to use thread.sleep..
playagain(fname);
}
void playagain(String fname){
        try {

    pl.stop();
    pl.deallocate();
   pl.close();

} catch (Exception ex) {}
 //change file name and stream and..
        playq(mp3f);
    }
4

1 回答 1

2

您的代码不应尝试catch块中播放代码 - 一方面,只有在生成异常时才会调用它(您通常也不应该笼统地捕捉Exception- 使用更具体的东西)。

你确定不能Thread.sleep()?当然,无论如何您都不会真的想要(例如,如果用户可以暂停剪辑......)。

相反,研究使用PlayerListener接口,并监听END_OF_MEDIA事件。

一个非常基本的(例如,这没有经过测试,并且需要更多的工作)示例:

public class PlayerRunner implements PlayerListener {

    private final String[] songFiles;
    private int songIndex = 0;

    public PlayerRunner(String[] songs) {
        this.songFiles = songs;
    }

    public void start() {
        playerUpdate(null, null, null);
    }

    // This method is required by the PlayerListener interface
    public void playerUpdate(Player player, String event, Object eventData) {
        // The first time through all parameters will be blank/null...
        boolean nextSong = (event == null);
        if (event == PlayerListener.END_OF_MEDIA) {
            player.stop();
            player.dallocate();
            player.close();
            nextSong = index < songIndex.length;
        }

        if (nextSong) {
            String fileName = songFiles[index++];
            if (fileName != null) {
                Player pl = Manager.createPlayer(fileName, "audio/mpeg");
                pl.addPlayerListener(this);
                pl.realize();
                pl.prefetch();
                pl.start();
            }
        }
    }
}

请注意,我没有完全正确地执行此操作 - 例如,我没有进行异常处理。另外,在不了解您的情况的情况下,我不知道还有什么需要担心的。这应该只是一个简单的答案,让您开始了解您应该去哪里。

(另外,我从未使用过 JME 的媒体播放器,所以我不知道关于 GC 的任何警告等)。

于 2011-09-19T20:21:53.987 回答