I get PCM data from a server. What is the best way to play them one after another? I currently call the following function for each sample batch that I get:
function playSamples( samples ) {
let count = samples.length / 2;
let leftData = new Float32Array( count );
let rightData = new Float32Array( count );
for ( let t = 0; t < count; ++ t ) {
leftData[ t ] = samples[ t * 2 + 0 ] / 0x7FFF;
rightData[ t ] = samples[ t * 2 + 1 ] / 0x7FFF;
}
let audioBuffer = this.context.createBuffer( 2, count, this.frequency );
audioBuffer.getChannelData( 0 ).set( leftData );
audioBuffer.getChannelData( 1 ).set( rightData );
let sourceNode = this.context.createBufferSource( );
sourceNode.buffer = audioBuffer;
sourceNode.connect( this.context.destination );
sourceNode.start( this.endTime );
this.endTime += audioBuffer.duration;
}
Basically, I setup a new buffer for each batch, that I schedule to play right at the end of the previous batch. It kinda works, but the audio isn't good enough, due to a lot of noise which I expect come from clumsy concatenation of the samples. Is there a better way to do what I want?