I have been trying to play a wav
file which is received from the server as a base64
string.
Everything works perfectly but there’s a click sound at the beginning of the audio. I have checked the base64s string is corrupted or not here and it seems fine.
So how to get rid of that click sound?
A complete working code is given here with base64 string.
NB: Wav is a 16bit pcm(pcm_s16le) audio with sample rate as 24000
.
socket.on('playAudio', function (msg) {
// msg.data is a base64 string
var byteChars = atob(msg.data);
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioCtx = new AudioContext({latencyHint: 'interactive',sampleRate: 24000})
// console.log(byteChars);
var byteNumbers = new Array(byteChars.length);
for (let i = 0; i <= byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var frameCount = byteArray.length/2;
console.log("framecount:",frameCount)
var myAudioBuffer = audioCtx.createBuffer(1,frameCount, 24000);
var nowBuffering = myAudioBuffer.getChannelData(0, 24000);
for (let i = 0; i < frameCount; i++){
var byteA = byteArray[i * 2];
var byteB = byteArray[i * 2 + 1];
var result = (((byteB & 0xFF) << 8) | (byteA & 0xFF));
var sign = byteB & (1 << 8);
var x = ((byteB & 0xFF) << 8 | (byteA & 0xFF));
if (sign) result = 0xFFFF0000 | x;
nowBuffering[i] = ((result + 32768) % 65536 - 32768) / 32768.0;
}
var source = audioCtx.createBufferSource();
source.buffer = myAudioBuffer;
source.connect(audioCtx.destination);
source.start();
});