Search code examples
javaaudiomixing

Mixing Audio Files in Java


I am creating this program in Java that import X number of Audio files and mix them in 1 audio file.

Example:

Import: "Audio1.wav", "Audio2.wav".
Mix them.
Export: "Result.wav"

Until now i have the import and export methods, my problem is mixing the files into 1 file.

Edit: Some pice of code.

private static File openDialog(){
    JFileChooser open = new JFileChooser();
    int returnVal = open.showOpenDialog(open);
    if (returnVal == JFileChooser.APPROVE_OPTION){
        return open.getSelectedFile();
    }
    return open.getSelectedFile();
}
private static File saveDialog(){
    JFileChooser save = new JFileChooser();
    FileFilter filter = new FileNameExtensionFilter("Audio files", ".wav");
    save.setFileFilter(filter);
    //save.addChoosableFileFilter(new AudioFilter());
    int returnVal = save.showSaveDialog(save);
    if (returnVal == JFileChooser.APPROVE_OPTION){
        return save.getSelectedFile();
    }
    return save.getSelectedFile();
}

private static List<File> importFile(File file){
    files.add(file);
    audioElements();
    return files;
}

This is how I import the files and save the result.


Solution

  • Mixing two audio streams can be as easy as taking the sum of the samples, that is

    result[i] = audio1[i] + audio2[i];
    

    This is assuming the audio is encoded in LPCM with the same sample size and frequency. If the audio is not LPCM (like µ-law, or A-law) you need a formula that takes the non-linear encoding into account. If the sample sizes are different you have to convert to the same size. If the sample frequencies are different you have to resample.