Reputation: 346
I need to normalize an 8 bit audio .wav file.
I used NAudio to load the file to a byte[]
. I successfully converted this to an sbyte[]
and recovered the sine bit. I then multiply this array (casting to a float
) to get the normalized value (0-255) hard limited.
Now I need to save it back as a byte[]
to let NAudio write it. The problem is, if I just cast,
source[i] = (byte)normalizedFloatArray[i];
The resulting saved .wav looks like this! Ouch.
"goofy wave"
Where might the problem lie?
Upvotes: 3
Views: 220
Reputation: 25623
Casting a byte
to an sbyte
causes positive values greater than sbyte.MaxValue
to overflow and become negative values, which may not be what you want. For example, while (sbyte)127
yields 127
, (sbyte)128
yields -128
. It may be that you want to translate the value range from [0, 255]
to [-128, 127]
, in which case you can simply offset each byte
by -128
:
signedByte = (sbyte)(unsignedByte + sbyte.MinValue)
Upvotes: 1
Reputation: 46
I think that happens because of how a byte gets converted to an sbyte. Example:
sbyte b1 = 100;
sbyte b2 = -100;
Console.WriteLine("{0} = {1}", b1, (byte)b1);
Console.WriteLine("{0} = {1}", b2, (byte)b2);
This outputs the following:
100 = 100
-100 = 156
So if your wave looks the following in sbytes:
{ 0, 50, 100, 50, 0, -50, -100, -50, 0 }
The output will be the following in bytes:
{ 0, 50, 100, 50, 206, 156, 206, 0 }
Upvotes: 2