Play WAV files one after the other in Java

拥有回忆 提交于 2019-12-01 13:44:05

This code is a bit low-level, but it works:

    byte[] buffer = new byte[4096];
    for (File file : files) {
        try {
            AudioInputStream is = AudioSystem.getAudioInputStream(file);
            AudioFormat format = is.getFormat();
            SourceDataLine line = AudioSystem.getSourceDataLine(format);
            line.open(format);
            line.start();
            while (is.available() > 0) {
                int len = is.read(buffer);
                line.write(buffer, 0, len);
            }
            line.drain(); //**[DEIT]** wait for the buffer to empty before closing the line
            line.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Basically you open an AudioInputStream, read data and write it to a SourceDataLine. write method is blocking, so it will play files consequently.

You can try to use Clip for the same purpose.

Berty

The final answer (with drain):

public static void play(ArrayList<String> files){
    byte[] buffer = new byte[4096];
    for (String filePath : files) {
        File file = new File(filePath);
        try {
            AudioInputStream is = AudioSystem.getAudioInputStream(file);
            AudioFormat format = is.getFormat();
            SourceDataLine line = AudioSystem.getSourceDataLine(format);
            line.open(format);
            line.start();
            while (is.available() > 0) {
                int len = is.read(buffer);
                line.write(buffer, 0, len);
            }
            line.drain();
            line.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!