Question

I have an array of generated samples of noise and i need to convert them to PCM format 8,16,32bit. I know how to do it when range is [0;max] but have problem when lower limit is negative.

This is how I do it for the range [0,max]:

byte quantize(double sample, double max_value)
{
    return (byte)((sample / max_value) * 255.0);
}
Was it helpful?

Solution 2

Since you can do it for the range [0,max] but not [a,b], shift the sample and range. (Note, this assumes that the quantization is linear.)

// from question.
byte quantize(double sample, double max_value)
{
    return (byte)((sample / max_value) * 255.0);
}


byte quantize( double sample, double min, double max )
{
    return quantize( sample - min, max - min );
}

OTHER TIPS

Let be x in [-a, a].
Then (x+a)/2a is in [0,1].
So 256(x+a)/2a is in [0,256].
So floor(256(x+a)/2a) is in {0, 1, 2, ..., 256}.
If you get 256, clamp to 255.

General purpose functions:

//Map x in [0,1] to {0, 1, ..., 255}
byte quantize(double x)
{
    x = (int)Math.Floor(256 * x);
    if (x < 0) return 0;
    else if (x > 255) return 255;
    else return (byte)x;
}

//Map x in [min,max] to {0, 1, ..., 255}
byte quantize(double x, double min, double max)
{
    return quantize((x - min) / (max - min));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top