Search code examples
node.jsaudiostreampcm

Pipe PCM-Streams into one function


I have two PCM-streams (decoder1 + decoder2):

var readable1 = fs.createReadStream("track1.mp3");
var decoder1 = new lame.Decoder({
    channels: 2,
    mode: lame.STEREO
});
readable1.pipe(decoder1);

and

var readable2 = fs.createReadStream("track2.mp3");
var decoder2 = new lame.Decoder({
    channels: 2,
    mode: lame.STEREO
});
readable2.pipe(decoder2);

Now I want to pipe the streams into one mix-function, where I can use the buffer-function like:

function mixStream(buf1, buf2, callback) {
    // The mixStream-Function is not implemented yet (dummy)
    var out = new Buffer(buf1.length);
    for (i = 0; i < buf1.length; i+=2) {
        var uint = Math.floor(.5 * buf1.readInt16LE(i));
        out.writeInt16LE(uint, i);
    }

    this.push(out);
    callback();
}

I need something like

mixStream(decoder1.pipe(), decoder2.pipe(), function() { }).pipe(new Speaker());

for output to speaker. Is this possible?


Solution

  • Well, pipe() function actually means a stream is linked to another, a readable to a writable, for instance. This 'linking' process is to write() to the writable stream once any data chunk is ready on the readable stream, along with a little more complex logic like pause() and resume(), to deal with the backpressure.

    So all you have to do is to create a pipe-like function, to process two readable streams at the same time, which drains data from stream1 and stream2, and once the data is ready, write them to the destination writable stream.

    I'd strongly recommend you to go through Node.js docs for Stream.

    Hope this is what you are looking for :)