我正在尝试互相播放一些WAV个文件。我试过这个方法:
for (String file : audioFiles) {
new AePlayWave(file).start();
}
但是,它同时播放所有这些。所以我需要一个看起来像这样的函数:
public void play(Vector<String> audioFiles);
向量包含文件,例如:"test1.wav"
,"test2.wav"
我一直在寻找超过四个小时,但我似乎无法找到一个有效的解决方案:(
我还尝试将WAV文件连接到一个AudioInputStream。它没有给出任何编译器错误,但声音完全搞砸了。代码:
public static AudioInputStream concat(Vector<String> files) throws UnsupportedAudioFileException, IOException {
AudioInputStream total = AudioSystem.getAudioInputStream(new File(files.get(0)));
for (int i = 1; i < files.size(); i++) {
AudioInputStream clip = AudioSystem.getAudioInputStream(new File(files.get(i)));
total = new AudioInputStream(new SequenceInputStream(total, clip),
total.getFormat(),
total.getFrameLength() + clip.getFrameLength());
}
return total;
}
修改
即使我尝试将两个第一个文件放在一起,也会失败:
public static AudioInputStream concat(Vector<String> files) throws UnsupportedAudioFileException, IOException {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(files.get(0)));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(files.get(1)));
AudioInputStream total = new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
return total;
}
答案 0 :(得分:2)
这段代码有点低级,但有效:
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();
}
}
基本上你打开一个AudioInputStream,读取数据并将其写入SourceDataLine。 write
方法阻塞,因此它将播放文件。
您可以尝试将Clip
用于相同目的。
答案 1 :(得分:0)
最终答案(排水):
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();
}
}
}