Вот класс, который я сделал:
class MixedSound extends Thread {
protected AudioFormat format; //Both streams must have same format
protected AudioInputStream sound1;
protected AudioInputStream sound2;
protected static SourceDataLine ausgabe;
protected DataLine.Info data;
public MixedSound(String path1, String path2) {
try {
sound1 = AudioSystem.getAudioInputStream(new File(path1));
sound2 = AudioSystem.getAudioInputStream(new File(path2));
format=sound1.getFormat(); //I assume both streams have same format
data=new DataLine.Info(SourceDataLine.class,format);
ausgabe=(SourceDataLine) AudioSystem.getLine(data);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException bug) {
System.err.println(bug);
}
}
public synchronized void play() throws IOException, LineUnavailableException {
ausgabe.open(format,1024);
ausgabe.start();
byte[] buffer1=new byte[1024];
byte[] buffer2=new byte[1024];
byte[] mixed=new byte[1024];
int bytes_sound1=sound1.read(buffer1,0,buffer1.length);
int bytes_sound2=sound2.read(buffer2,0,buffer2.length);
while (bytes_sound1 != -1 || bytes_sound2 != -1) {
for (int i=0; i < mixed.length; i++) {
mixed[i]=(byte)Math.min(0.999f,((float)buffer1[i]+(float)buffer2[i])); //Mix them
}
ausgabe.write(mixed, 0, Math.max(bytes_sound1, bytes_sound2));
buffer1=new byte[1024]; //Clean buffer
buffer2=new byte[1024]; //Clean buffer
bytes_sound1=sound1.read(buffer1,0,buffer1.length);
bytes_sound2=sound2.read(buffer2,0,buffer2.length);
}
ausgabe.drain();
ausgabe.close();
}
@Override
public synchronized void run() {
try {
play();
} catch (IOException | LineUnavailableException ex) {
System.err.println(ex);
}
}
}
Он смешивает два звука, добавляя их громкости.
Используйте это так:
MixedSound sound=new Sound("sound1.wav","sound2.wav");
sound.start(); //Play it
System.out.println("Started playing sound"); //Do stuff at same time
Надеюсьпомогает.