How to mix PCM audio sources (Java)?

半世苍凉 提交于 2019-12-04 10:24:26

In the linked article the author assumes A and B to represent entire streams of audio. More specifically X means the maximum abs value of all of the samples in stream X - where X is either A or B. So what his algorithm does is scans the entirety of both streams to compute the max abs sample of each and then scales things so that the output theoretically peaks at 1.0. You'll need to make multiple passes over the data in order to implement this algorithm and if your data is streaming in then it simply will not work.

Here is an example of how I think the algorithm to work. It assumes that the samples have already been converted to floating point to side step the issue of your conversion code being wrong. I'll explain what is wrong with it later:

 double[] samplesA = ConvertToDoubles(samples1);
 double[] samplesB = ConvertToDoubles(samples2);
 double A = ComputeMax(samplesA);
 double B = ComputeMax(samplesB);

 // Z always equals 1 which is an un-useful bit of information.
 double Z = A+B-A*B;

 // really need to find a value x such that xA+xB=1, which I think is:
 double x = 1 / (Math.sqrt(A) * Math.sqrt(B));

 // Now mix and scale the samples
 double[] samples = MixAndScale(samplesA, samplesB, x);

Mixing and scaling:

 double[] MixAndScale(double[] samplesA, double[] samplesB, double scalingFactor)
 {
     double[] result = new double[samplesA.length];
     for (int i = 0; i < samplesA.length; i++)
         result[i] = scalingFactor * (samplesA[i] + samplesB[i]);
 }

Computing the max peak:

double ComputeMaxPeak(double[] samples)
{
    double max = 0;
    for (int i = 0; i < samples.length; i++)
    {
        double x = Math.abs(samples[i]);
        if (x > max)
            max = x;
    }
    return max;
}

And conversion. Notice how I'm using short so that the sign bit is properly maintained:

double[] ConvertToDouble(byte[] bytes)
{
    double[] samples = new double[bytes.length/2];
    for (int i = 0; i < samples.length; i++)
    {
        short tmp = ((short)bytes[i*2])<<8 + ((short)(bytes[i*2+1]);
        samples[i] = tmp / 32767.0;
    }
    return samples;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!