0

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?

Maël Nison
  • 7,055
  • 7
  • 46
  • 77
  • When you say you get it from the server, do you mean you're effectively streaming it? You might want to consider building up a bit of a buffer (say, 5 seconds or something) before you start playback at all. That way, you've got some protection against underrun. – Kevin Ennis Jun 14 '15 at 20:43
  • Assuming no underrun on the stream, your code looks right to me as far as timing goes. But you need to make sure you get each chunk from the server with enough time left over to do all the work of converting from interleaved +/- 2048 to dual-mono (or whatever you want to call it) +/- 1 and scheduling playback. – Kevin Ennis Jun 14 '15 at 20:46
  • @KevinEnnis Actually, I'm generating these PCM data myself (I said from the server because it might be easier to visualize), so I don't think that underruns are the issue – Maël Nison Jun 14 '15 at 20:52
  • Hmm. Could you post a JSbin/JSFiddle? I'd be interested to hear the problem. – Kevin Ennis Jun 14 '15 at 22:06
  • @KevinEnnis I use this [codepen](http://codepen.io/anon/pen/GJvjrL) to test. The splitted samples work quite well on Firefox, but Chrome adds an heavy amount of noise, which is not present when concatenating all samples in one buffer. – Maël Nison Jun 15 '15 at 10:43

0 Answers0