I want to apply gain to my recordings(PCM 16bit). For this I have the following code:
for (int i=0; i<buffer.length/2; i++)
{ // 16bit sample size
short curSample = getShort(buffer[i*2], buffer[i*2+1]);
if(rGain != 1){
//apply gain
curSample *= rGain;
//convert back from short sample that was "gained" to byte data
byte[] a = getByteFromShort(curSample);
buffer[i*2] = a[0];
buffer[i*2 + 1] = a[1];
}
If applied like this(multiplying each sample with the fraction number), I get discontinues when playback(hearing like an old walkie-talkie). Is there some formula to vary my gain factor on each sample? I assume there is some maxValue and minValue for the range of samples (I guess [-32768, +32767]) and using these values in some formula I can get a variated gain factor to apply to the current sample.
//EDIT: added
if (curSample>32767) {curSample=32767;}
if (curSample<-32768) {curSample=-32768;}
full method
aRecorder.read(buffer, 0, buffer.length);
for (int i=0; i<buffer.length/2; i++)
{ // 16bit sample size
short curSample = getShort(buffer[i*2], buffer[i*2+1]);
if(rGain != 1){
//apply gain
curSample *= rGain;
if (curSample>32767) {curSample=32767;}
if (curSample<-32768) {curSample=-32768;}
//convert back from short sample that was "gained" to byte data
byte[] a = getByteFromShort(curSample);
buffer[i*2] = a[0];
buffer[i*2 + 1] = a[1];
}
But still hears odd(noise + discontinues like an old walkie-talkie).
Any help would be appreciated,
Thanks.