package com.talixa.specan.dsp;
import java.io.IOException;
import com.talixa.audio.wav.WaveFile;
import com.talixa.audio.wav.WaveGenerator;
public class AudioMixer {
/*
* To mix PCM samples, simply sum both values and divide by 2
* Or, if both files are in different ranges, sum the number
*/
public enum MixerMode {SUM, AVERAGE};
// input and output are PCM samples
public static short[] mix(short[] background, short[] foreground, MixerMode mode) {
int maxLength = background.length > foreground.length ? background.length : foreground.length;
short[] mixedData = new short[maxLength];
for(int i = 0; i < maxLength; ++i) {
short bg = i < background.length ? background[i] : 0;
short fg = i < foreground.length ? foreground[i] : 0;
// add pcm samples and divide by 2
int sum = bg + fg;
if (mode.equals(MixerMode.AVERAGE)) {
mixedData[i] = (short)(sum/2);
} else {
mixedData[i] = (short)sum;
}
}
return mixedData;
}
public static void mix(short[] background, short[] foreground, MixerMode mode, String outputFile) throws IOException {
short[] mixed = mix(background,foreground, mode);
byte[] byteData = SharedDSPFunctions.shortArrayToByteArray(mixed);
WaveFile w = WaveGenerator.generateWaveFromRaw16bitPcm(byteData);
w.outputToFile(outputFile);
}
public static void main(String args[]) {
try {
short[] sample1k = ToneGenerator.generateWave(1000, .1, 30);
short[] sample2k = ToneGenerator.generateWave(2000, .1, 30);
short[] sample500hz = ToneGenerator.generateWave(500, .2, 30);
short[] mix1 = mix(sample1k, sample2k, MixerMode.SUM);
mix(mix1, sample500hz, MixerMode.SUM, "c:\\test.wav");
} catch (IOException e) {
e.printStackTrace();
}
}
}