Gonzalo Acosta Gonzalo Acosta - 1 year ago 154
Java Question

Java Record / Mix two audio streams

i have a java application that records audio from a mixer and store it on a byte array, or save it to a file.
What I need is to get audio from two mixers simultaneously, and save it to an audio file (i am trying with .wav).
The thing is that I can get the two byte arrays, but don't know how to merge them (by "merge" i don't mean concatenate).
To be specific, it is an application that handles conversations over an USB modem and I need to record them (the streams are the voices for each talking person, already maged to record them separately).

Any clue on how to do it?

EDIT: Actual Code Added

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;

public class FileMixer {

Path path1 = Paths.get("/file1.wav");
Path path2 = Paths.get("/file2.wav");
byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);
byte[] out = new byte[byte1.length];

public FileMixer() {

byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);

for (int i=0; i<byte1.Length; i++)
out[i] = (byte1[i] + byte2[i]) >> 1;


Thanks in advice

Answer Source

To mix sound waves digitally, you add each corresponding data point from the two files together.

for (int i=0; i<source1.length; i++)
    result[i] = (source1[i] + source2[i]) >> 1;

In other words, you take item 0 from byte array 1, and item 0 from byte array two, add them together, and put the resulting number in item 0 of your result array. Repeat for the remaining values. To prevent overload, you may need to divide each resulting value by two.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download