Concatenate WAV files in Java
Here is a small snippet that will let you concatenate a list of WAV files. This only works for WAV files and is based on the assumption that all files are of the same format.
public Boolean concatenateFiles(List<String> sourceFilesList, String destinationFileName) throws Exception {
Boolean result = false;
AudioInputStream audioInputStream = null;
List<AudioInputStream> audioInputStreamList = null;
AudioFormat audioFormat = null;
Long frameLength = null;
try {
// loop through our files first and load them up
for (String sourceFile : sourceFilesList) {
audioInputStream = AudioSystem.getAudioInputStream(new File(sourceFile));
// get the format of first file
if (audioFormat == null) {
audioFormat = audioInputStream.getFormat();
}
// add it to our stream list
if (audioInputStreamList == null) {
audioInputStreamList = new ArrayList<AudioInputStream>();
}
audioInputStreamList.add(audioInputStream);
// keep calculating frame length
if(frameLength == null) {
frameLength = audioInputStream.getFrameLength();
} else {
frameLength += audioInputStream.getFrameLength();
}
}
// now write our concatenated file
AudioSystem.write(new AudioInputStream(new SequenceInputStream(Collections.enumeration(audioInputStreamList)), audioFormat, frameLength), Type.WAVE, new File(destinationFileName));
// if all is good, return true
result = true;
} finally {
if (audioInputStream != null) {
audioInputStream.close();
}
if (audioInputStreamList != null) {
audioInputStreamList = null;
}
}
return result;
}
While the core code is good for most people, I’m sure the nuances of your needs are different than mine so you can modify or extend that above as necessary.
Happy coding!