java
public static void main(String[] args) {
File file1 = new File("D:\\配音\\LOL稳健4.mp3");
File file2 = new File("D:\\配音\\LOL稳健4-2.mp3");
File file3 = new File("D:\\配音\\LOL稳健444.mp3");
// 创建要合并的音频文件对象列表
List<File> sourceFiles = new ArrayList<>();
sourceFiles.add(file1);
sourceFiles.add(file2);
mergeAudioFiles(sourceFiles, file3);
}
private static void mergeAudioFiles(List<File> audioFiles, File outputFile) {
try {
long totalLength = 0;
AudioFormat audioFormat = null;
AudioInputStream audioInputStream = null;
List<AudioInputStream> audioInputStreams = new ArrayList<>();
// 读取每个音频文件,获取其音频格式和音频流
for (File audioFile : audioFiles) {
audioInputStream = AudioSystem.getAudioInputStream(audioFile);
totalLength += audioInputStream.getFrameLength();
audioFormat = audioInputStream.getFormat();
audioInputStreams.add(audioInputStream);
}
// 创建新的音频格式和流
boolean isSigned = audioFormat.getEncoding() == AudioFormat.Encoding.PCM_SIGNED;
AudioFormat newAudioFormat = new AudioFormat(audioFormat.getSampleRate(),
audioFormat.getSampleSizeInBits(),
audioFormat.getChannels(),
isSigned,
audioFormat.isBigEndian());
AudioInputStream mergedAudioStream = new AudioInputStream(
new SequenceInputStream(Collections.enumeration(audioInputStreams)),
newAudioFormat,
totalLength
);
// 写入合并后的音频流到输出文件
AudioSystem.write(mergedAudioStream, AudioFileFormat.Type.WAVE, outputFile);
// 关闭所有音频流
for (AudioInputStream ais : audioInputStreams) {
ais.close();
}
mergedAudioStream.close();
} catch (UnsupportedAudioFileException | IOException e) {
e.printStackTrace();
}
}