We recently received a couple of 24-bit PCM source files, and the original PCM to WAV tool in Recoder only supports 8-bit and 16-bit, so we upgraded to 24-bit PCM source files.

May be the search method is not right, search for a long time did not find 24 to 16 bits of the algorithm, but fortunately also good luck to see a title does not want to close the article there is a complete set of conversion algorithm.

Algorithm source

24 bits PCM into a 32-bit floating point Numbers refer to the article: www.codeproject.com/articles/50… The Convert24BitToFloat function in there, converted to a 32 bit float, can easily be converted to 16 or 8 bits.

Js version 24 bit PCM to 8 bit, 16 bit code

var pcm24=... Uint8ArrayBinary array... ;var pcm16=new Int16Array(pcm24.length/3);
var pcm8=new Uint8Array(pcm24.length/3);

for(var i=0,j=0; j<pcm24.length; i++){//24bit PCM is converted to floating point
	var n=((pcm24[j++] | (pcm24[j++]<<8) | (pcm24[j++]<<16)) < <8) > >8;
	n=n/16777216;
	
	// Float is converted to 16 bits
	pcm16[i]=n*0x7FFF;
	
	// Float is converted to 8 bits
	pcm8[i]=((n*0x7FFF) > >8) + 128;
};
Copy the code

The 24-bit PCM has been converted to 16-bit and 8-bit in the code, which is very simple and easy to port to other languages.

Js version 8 bit, 16 bit PCM converted to 24 bit

Do a reverse operation based on the code above:

var pcm16=... Int16Array. ;var pcm24=new Uint8Array(pcm16.length*3);

for(var i=0,j=0; i<pcm16.length; i++){var n=pcm16[i] / 0x7FFF * 16777216;
	//var n=((pcm8[i]-128) << 8) / 0x7FFF * 16777216; // The extra step of 8 bits is converted to 16 bits first

	pcm24[j++]=n & 0xff;
	pcm24[j++]=(n & 0xff00) > >8;
	pcm24[j++]=(n & 0xff0000) > >16;
}
Copy the code

Attached: Browser console download data file code

var b=new Blob([pcm16]);
var a=document.createElement("a");
a.href=URL.createObjectURL(b)
a.download="test.pcm";
a.click();
Copy the code

Related implementation

This code has been used in H5 recording open source library Recorder naked (RAW, WAV)PCM to WAV playback test and transcoding online tools, click this can be online conversion OF PCM files.

【 the 】.