0

I am trying to stream MP3 file from a nodeJS server using BinaryJS - http://binaryjs.com/

But, when I am decoding the buffers on the client side they are seems to be overlapping, Meaning that the new chunk of data is being played few milliseconds before the previous one ended, causing the audio to lag.

is there any way to make the client wait until the current buffer is finished before starting the new one?

Server:

var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');
var server = BinaryServer({port: 9000});

server.on('connection', function(client){

    var file = fs.createReadStream(__dirname + '/Song.mp3', {
        'flags': 'r',
        'bufferSize': 4 * 1024
        });
    });

    client.send(file);
});

Client:

var client = new BinaryClient('ws://localhost:9000');

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();


client.on('stream', function (stream, meta) {
    var parts = [];
    var last = 0;
    stream.on('data', function (data) {

        var source = context.createBufferSource();
        context.decodeAudioData(data, function (buf) {
                source.buffer = buf;
                source.connect(context.destination);
                source.loop = false;
                source.start(last);
                last += buf.duration;
                source.onended = function() {
                console.log('Your audio has finished playing');
            };
        },

        function (e) {
            "Error with decoding audio data" + e.err
        });
    parts.push(data);
    });
    stream.on('end', function () {
        console.log(parts);
    });
});  
Ronco
  • 109
  • 1
  • 10

1 Answers1

0

Not sure about this, but instead of initializing last to 0, you might want to initialize it to context.currentTime.

Raymond Toy
  • 5,490
  • 10
  • 13